DataFrame.set_index has no effect

2

set_index does not work on Pandas DataFrame as indicated in the documentation.

I'm using:

  • Pandas version 0.20.3
  • Python version 3.6

I tried the example in the documentation:

link

import numpy as np  
import pandas as pd  

df2 = pd.DataFrame({'month': [1, 4, 7, 10],  
    'year': [2012, 2014, 2013, 2014],  
    'sale':[55, 40, 84, 31]})  
print('\ndf2 dataframe de ensayo')  
print(df2)  

df2.set_index('month')  
print("\ndf2: set_index='month'")  
print("\tNo toma la columna 'month' como indice")  
print(df2)  

df3 = pd.DataFrame({  
    'year': [2012, 2014, 2013, 2014],  
    'sale':[55, 40, 84, 31]  
})  
df3.index = pd.DataFrame({'month':[1, 4, 7, 10]})  
print('\ndf3')  
print(df3)  

The output is:

df2 dataframe de ensayo  
   month  sale  year  
0      1    55  2012  
1      4    40  2014  
2      7    84  2013  
3     10    31  2014  

df2: set_index='month'  
    No toma la columna 'month' como indice  
   month  sale  year  
0      1    55  2012  
1      4    40  2014  
2      7    84  2013  
3     10    31  2014  

df3  
    sale  year  
1     55  2012  
4     40  2014  
7     84  2013  
10    31  2014  
    
asked by jab70 14.11.2017 в 23:25
source

1 answer

0

Please note that the documentation simulates the use of an interactive interpreter. pandas.dataFrame.set_index does not modify the DataFrame by default, but returns one new with the correctly modified index (this return is what the interactive interpreter shows).

To modify the DataFrame without creating a new one you need to specify the argument inplace as True :

  

inplace : boolean, default False

     

Modify the DataFrame in place (do not create a new object)

That is, your code should be:

import pandas as pd  


df2 = pd.DataFrame({'month': [1, 4, 7, 10],  
                     'year': [2012, 2014, 2013, 2014],  
                     'sale': [55, 40, 84, 31]})    
df2.set_index('month',  inplace = True)   
print(df2)  

Your exit is the expected one:

        sale  year
month            
1        55  2012
4        40  2014
7        84  2013
10       31  2014
    
answered by 14.11.2017 / 23:56
source