[英]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 ![]() |
A![]() |
PQ ![]() |
300 ![]() |
My output should be like:-我的 output 应该是这样的:-
Col![]() |
Val![]() |
---|---|
A![]() |
500 ![]() |
CD![]() |
200 ![]() |
PQ ![]() |
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.