在 Pandas 中将行名称转换为列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25457920/
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:23:12  来源:igfitidea点击:

Convert row names into a column in Pandas

pythonpandas

提问by pdubois

I have the following Pandas data frame:

我有以下 Pandas数据框

print(df)

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

What I want to do is to convert the row names bar, bix, ...into columns such that in the end I have something like this:

我想要做的是将行名称bar, bix, ...转换为列,这样最后我就有了这样的东西:

    newhead     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

How can I achieve that?

我怎样才能做到这一点?

回答by unutbu

df.index.name = 'newhead'
df.reset_index(inplace=True)

yields

产量

  newhead  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