Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a specific column into row names in Pandas

Tags:

python

pandas

I have this DF

print(df)
    head0     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

What I want to do use to use head0 as row names:

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

How can I achieve that?

like image 298
pdubois Avatar asked Jan 14 '15 06:01

pdubois


2 Answers

Just to expand on nitin's answer set_index :

In [100]:

df.set_index('head0')

Out[100]:
       head1  head2  head3
head0                     
bar       32      3    100
bix       22    NaN    NaN
foo       11      1    NaN
qux      NaN     10    NaN
xoo      NaN      2     20

Note that this returns the df, so you either have to assign back to the df like: df = df.set_index('head0') or set param inplace=True: df.set_index('head0', inplace=True)

You can also directly assign to the index:

In [99]:

df.index = df['head0']
df
Out[99]:
      head0  head1  head2  head3
head0                           
bar     bar     32      3    100
bix     bix     22    NaN    NaN
foo     foo     11      1    NaN
qux     qux    NaN     10    NaN
xoo     xoo    NaN      2     20

Note that doing the above will require you to drop the extraneous 'head0' column which can be done by calling drop like so: df.drop('head0', axis=1)

like image 192
EdChum Avatar answered Sep 18 '22 16:09

EdChum


You can use the set_index method for the dataframe, like so

df.set_index(df.head0)
like image 32
nitin Avatar answered Sep 20 '22 16:09

nitin