简体   繁体   English

使用 pandas 将多列插入单列

[英]Insert multiple columns into a single column using pandas

I am converting a SAS code to python and got stuck here.我正在将 SAS 代码转换为 python 并卡在此处。

My input table is like:-我的输入表是这样的:-

St英石 sgmt警卫队 Val瓦尔
A一种 CD光盘 200 200
A一种 PQ PQ 300 300

My output should be like:-我的 output 应该是这样的:-

Col上校 Val瓦尔
A一种 500 500
CD光盘 200 200
PQ PQ 300 300

500 is the sum of values of same category 500 是同一类别值的总和

You can melt to combine the "St" and "sgmt" columns, then GroupBy.sum to aggregate per name:您可以melt合并“St”和“sgmt”列,然后GroupBy.sum按名称聚合:

(df
 .melt('Val', value_name='Col')
 .groupby('Col', as_index=False)
 ['Val'].sum()
)

output: output:

  Col  Val
0   A  500
1  CD  200
2  PQ  300

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM