4

I get a DataFrame from a library with an index already set to one of the data columns. What would be the easiest way to set it to another column, preserving the original index column.

Input:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]],columns=['a','b','c'])
df = df.set_index('a')

   b  c
a      
1  2  3
4  5  6
7  8  9

Output: (f.e. changing index from column a to column b)

   a  c
b      
2  1  3
5  4  6
8  7  9
aydow
  • 3,673
  • 2
  • 23
  • 40
Krzysztof Słowiński
  • 6,239
  • 8
  • 44
  • 62

1 Answers1

7

Chain reset_index and then set_index:

df = df.reset_index().set_index('b')

Or separately:

df.reset_index(inplace=True)
df.set_index('b', inplace=True)

Resulting df

   a  c
b      
2  1  3
5  4  6
8  7  9
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
sacuL
  • 49,704
  • 8
  • 81
  • 106