pdubois
pdubois

Reputation: 7800

Convert a specific column into row names in 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?

Upvotes: 8

Views: 12068

Answers (2)

EdChum
EdChum

Reputation: 394439

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)

Upvotes: 10

nitin
nitin

Reputation: 7358

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

df.set_index(df.head0)

Upvotes: 3

Related Questions