Sam Rds Sam Rds - 5 months ago 12
Python Question

Transforming a column index in Python pandas

I have the following DataFrame:

index PUBLICO CLASSIFICACAO_PUBLICO
0 19 143643 1
1 34 111879 2
2 31 50382 3
3 9 49204 4
4 32 37541 5
5 4 36095 6


I need convert the index name column to index column.

For example:

index PUBLICO CLASSIFICACAO_PUBLICO
19 143643 1
34 111879 2
31 50382 3
9 49204 4
32 37541 5
4 36095 6


I try use
df.set_index('index')
, but it didn't work.

The column with the name
index
previously was the index column the DataFrame, but I used
reset_index()
; now I need to do the reverse.

Answer

The method set_index doesn't work inplace. So that you have to reassign your dataframe, or to pass the option inplace = True:

df = df.set_index('index')

or

df.set_index('index',inplace = True)

see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html

Comments