pdubois
pdubois

Reputation: 7800

Convert row names into a column in Pandas

I have the following Pandas data frame:

print(df)

     head1  head2  head3
bar     32      3    100
bix     22    NaN    NaN
foo     11      1    NaN
qux    NaN     10    NaN
xoo    NaN      2     20

What I want to do is to convert the row names bar, bix, ... into columns such that in the end I have something like this:

    newhead     head1  head2  head3
0   bar         32      3    100
1   bix         22    NaN    NaN
2   foo         11      1    NaN
3   qux         NaN    10    NaN
4   xoo         NaN     2     20

How can I achieve that?

Upvotes: 29

Views: 31029

Answers (2)

Chang Ye
Chang Ye

Reputation: 1215

You can do it in one line.

df.rename_axis("newhead").reset_index()

Upvotes: 11

unutbu
unutbu

Reputation: 879869

df.index.name = 'newhead'
df.reset_index(inplace=True)

yields

  newhead  head1  head2  head3
0     bar     32      3    100
1     bix     22    NaN    NaN
2     foo     11      1    NaN
3     qux    NaN     10    NaN
4     xoo    NaN      2     20

Upvotes: 57

Related Questions