大 pandas 堆栈与行号 [英] pandas stack with row numbers

查看:77
本文介绍了大 pandas 堆栈与行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas DataFrame示例:

I have an example Pandas DataFrame:

          A         B         C         D
0  0.441040  0.235533 -0.899417  1.960367
1 -0.701764  2.343389  1.293865  0.556737
2 -0.511988 -0.260338  0.201938  1.154131
3  1.001099  1.077759 -0.006872 -0.961884
4  0.914676 -0.445287 -1.618399 -0.616381
5  0.360060 -0.082711  1.010578  1.071003

最后,我希望将某些列与上面关联的行号堆叠在一起.使用列选择和堆栈非常接近:

And what I would like in the end is to have certain columns stacked with the row number associated above. Using column selection and stack is very close:

 df[['B','C']].stack()

0  B    0.235533
   C   -0.899417
1  B    2.343389
   C    1.293865
2  B   -0.260338
   C    0.201938
3  B    1.077759
   C   -0.006872
4  B   -0.445287
   C   -1.618399
5  B   -0.082711
   C    1.010578

但是我希望将行号与每一行相关联,因为将下面的每一行与原始数据帧/表相关联非常重要:

But I would like the row numbers to be associated with each row as it will be important to relate each row below back to the original dataframe/table:

0  B    0.235533
0  C   -0.899417
1  B    2.343389
1  C    1.293865
2  B   -0.260338
2  C    0.201938
3  B    1.077759
3  C   -0.006872
4  B   -0.445287
4  C   -1.618399
5  B   -0.082711
5  C    1.010578

我不确定如何将df [[''B','C']].stack()转换为我想要的内容,并将其与每行关联的原始行号/索引.

I am not sure how to convert the df[['B','C']].stack() into what I want with the original row numbers/indexes associated with each row.

最后,我想将输出与行号关联写到CSV文件中.

In the end I want to write out the output to a CSV file with the row number associations.

推荐答案

pandas.DataFrame.reset_index将多级索引推入列中.它也可以在pandas.Series上使用.

pandas.DataFrame.reset_index pushes a multi-level index into the columns. It works on a pandas.Series too.

df[['B', 'C']].stack().reset_index()

这篇关于大 pandas 堆栈与行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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