Reputation: 7227
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
Upvotes: 4
Views: 4750
Reputation: 51335
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
Upvotes: 6