将特定的列转换为Pandas中的行名 [英] Convert a specific column into row names in Pandas

查看:64
本文介绍了将特定的列转换为Pandas中的行名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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

使用head0作为行名时我想做的事情:

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

我该如何实现?

推荐答案

只是为了扩展nitin的答案

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

请注意,这将返回df,因此您必须像df = df.set_index('head0')那样分配回df或设置参数inplace=True:df.set_index('head0', inplace=True)

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

请注意,执行上述操作将需要删除多余的"head0"列,这可以通过调用

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)

这篇关于将特定的列转换为Pandas中的行名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆