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?
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)
You can use the set_index method for the dataframe, like so
df.set_index(df.head0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With