Groupby Row元素和Tranpose熊猫数据框架。

问题描述 投票:2回答:1

在Python中,我有以下Pandas数据框架。

     Factor     Value
0    a          1.2
1    b          3.4
2    b          4.5
3    b          5.6
4    c          1.3
5    d          4.6

我想把它组织起来,其中:

  • 唯一的行标识符(因子col)成为列
  • 它们各自的值仍在所创建的列下

因素值不在一个组织中。

目标。

     A     B    C     D
0    1.2   3.4  1.3   4.6     
1          4.5
2          5.6  
3            
4       
5            
python pandas pandas-groupby
1个回答
2
投票

使用。set_indexunstackgroupby:

df.set_index(['Factor', df.groupby('Factor').cumcount()])['Value'].unstack(0)

产出:

Factor    a    b    c    d
0       1.2  3.4  1.3  4.6
1       NaN  4.5  NaN  NaN
2       NaN  5.6  NaN  NaN
© www.soinside.com 2019 - 2024. All rights reserved.