Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving index from one column to another in pandas data frame

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
like image 535
Krzysztof Słowiński Avatar asked Mar 06 '23 23:03

Krzysztof Słowiński


1 Answers

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
like image 153
sacuL Avatar answered Mar 23 '23 17:03

sacuL