当特定列具有重复行时,为列值重复创建列名

2024-06-17 12:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个需要旋转的数据帧(不确定这是否涉及堆叠或旋转…)

因此,如果在“年”、“月”和“组”列中有重复的值,我想将下面的列名称移动,以便为变量重复

如果这是原始数据框:

Year  Month  Group  Variable  feature1  feature2  feature3  
2010    6      1      1           12        23        56
2010    6      1      2           34        56        25 

结果将是:

Year  Month  Group  Variable1  feature1_1  feature2_1  feature3_1  Variable2  feature1_2    feature2_2  feature3_2 
 2010    6      1      1           12        23        56               2           34           56       25

我正在寻找这些线索-任何提示/帮助都非常感谢

谢谢

伊兹


Tags: 数据名称原始数据groupvariableyearmonth线索
1条回答
网友
1楼 · 发布于 2024-06-17 12:22:31

IIUC,如果您想将它从long转换回wide,您可以使用cumcount获取addtional键,然后重新整形

df['New']=(df.groupby(['Year','Month','Group']).cumcount()+1).astype(str)
w=df.set_index(['Year','Month','Group','New']).unstack().sort_index(level=1,axis=1)
w.columns=pd.Index(w.columns).str.join('_')
w
Out[217]: 
                  Variable_1  feature1_1  feature2_1  feature3_1  Variable_2  \
Year Month Group                                                               
2010 6     1               1          12          23          56           2   
                  feature1_2  feature2_2  feature3_2  
Year Month Group                                      
2010 6     1              34          56          25  

相关问题 更多 >