Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert row names into a column in Pandas

Tags:

python

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?

like image 838
pdubois Avatar asked Aug 23 '14 02:08

pdubois


People also ask

How do I convert rows to columns in pandas?

The transpose() function is used to transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. If True, the underlying data is copied.

How do you turn a row into a pandas list?

The command to convert Dataframe to list is pd. DataFrame. values. tolist().


2 Answers

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
like image 146
unutbu Avatar answered Oct 07 '22 04:10

unutbu


You can do it in one line.

df.rename_axis("newhead").reset_index()
like image 41
Chang Ye Avatar answered Oct 07 '22 03:10

Chang Ye