I need to create columns where sum other columns based on conditional of other column values. The requirement is as below.
I have the following table:
key code1 code2 code3 code4 value1 value2 value3 value4
0 101 101 101 101 1000 1000 1000 1000
1 101 101 101 201 1000 1000 1000 1000
2 101 101 201 201 1000 1000 1000 1000
3 101 201 201 201 1000 1000 1000 1000
4 101 201 201 301 1000 1000 1000 1000
5 101 201 301 301 1000 1000 1000 1000
6 101 301 301 301 1000 1000 1000 1000
7 101 101 101 301 1000 1000 1000 1000
8 101 201 301 0 1000 1000 1000 0
9 101 301 0 0 1000 1000 0 0
....
I need to create one column to sum the column value(value1, value2, value3, value4) considering the columns code (code1, code2, code3, code4). The result should be like this:
key code1 code2 code3 code4 value1 value2 value3 value4 sum_code_101 sum_code_201 sum_code_301
0 101 101 101 101 1000 1000 1000 1000 4000 0 0
1 101 101 101 201 1000 1000 1000 1000 3000 1000 0
2 101 101 201 201 1000 1000 1000 1000 2000 2000 0
3 101 201 201 201 1000 1000 1000 1000 1000 3000 0
4 101 201 201 301 1000 1000 1000 1000 1000 2000 1000
5 101 201 301 301 1000 1000 1000 1000 1000 1000 2000
6 101 301 301 301 1000 1000 1000 1000 1000 0 3000
7 101 101 101 301 1000 1000 1000 1000 3000 0 1000
8 101 201 301 0 1000 1000 1000 0 1000 1000 1000
9 101 301 0 0 1000 1000 0 0 1000 0 1000
As the real table has 25 different codes (101, 201, 301...) I need to create 25 columns to sum their values.
Any help will be very appreciated.
Copyright Notice:Content Author:「M_F」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62094687/create-columns-where-sum-other-columns-based-on-conditional-of-other-column-valu