'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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway