在 Pandas 中将特定列转换为行名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27937037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:50:41  来源:igfitidea点击:

Convert a specific column into row names in Pandas

pythonpandas

提问by pdubois

I have this DF

我有这个 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 head0as row names:

我想要做的head0用作行名:

    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?

我怎样才能做到这一点?

回答by EdChum

Just to expand on nitin's answer set_index:

只是为了扩展 nitin 的回答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)

请注意,这将返回 df,因此您必须将其分配回 df,例如:df = df.set_index('head0')或设置 param inplace=Truedf.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 droplike so: df.drop('head0', axis=1)

请注意,执行上述操作将要求您删除无关的“head0”列,这可以通过如下调用来完成dropdf.drop('head0', axis=1)

回答by nitin

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

您可以对数据帧使用 set_index 方法,就像这样

df.set_index(df.head0)