简体   繁体   中英

Insert multiple columns into a single column using pandas

I am converting a SAS code to python and got stuck here.

My input table is like:-

St sgmt Val
A CD 200
A PQ 300

My output should be like:-

Col Val
A 500
CD 200
PQ 300

500 is the sum of values of same category

You can melt to combine the "St" and "sgmt" columns, then GroupBy.sum to aggregate per name:

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

output:

  Col  Val
0   A  500
1  CD  200
2  PQ  300

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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