action | indicator | channel | greenfield | trucking | studio
-------------------------------------------------------------
approved| cash | DM | .0067 | .2356 | .1451
approved| cash | DM | .1067 | .4549 | .4881
approved| card | EM | .2067 | .8424 | .0264
approved| card | EM | .3067 | .5949 | .1564
approved| online | RM | .4555 | .4987 | .5616
...
Hello! From the table above, I've been trying to loop through each column then add based on channel, indicator, and action with no avail. Here is a manual code I've been using in it's place:
data.loc[(data['action'] == "approved") & (data['indicator'] == "cash") &
(data['channel'] == "DM"), 'greenfield '].sum()
The end result should look like (I am creating another table, hence the column name changes):
Segment | Name | greenfield | trucking | studio
------------------------------------------------
DM |Approved| .1134 | .6905 | .6332
EM |Approved|..... |..... |.....
Any help in turning the above into a loop would be greatly appreciated!
.group_by
seems to be working:
# Constructing the dataframe:
d = {'action': ['approved', 'approved', 'approved', 'approved', 'approved'],
'indicator': ['cash', 'cash', 'card', 'card', 'online'],
'channel': ['DM', 'DM', 'EM', 'EM', 'RM'],
'greenfield': [0.0067, 0.1067, 0.2067, 0.3067, 0.4555],
'trucking': [0.2356, 0.4549, 0.8424, 0.5949, 0.4987],
'studio': [0.1451, 0.4881, 0.0264, 0.1564, 0.5616]}
data = pd.DataFrame(d)
data.groupby(['action', 'indicator', 'channel']).sum().reset_index()
action | indicator | channel | greenfield | trucking | studio | |
---|---|---|---|---|---|---|
0 | approved | card | EM | 0.5134 | 1.4373 | 0.1828 |
1 | approved | cash | DM | 0.1134 | 0.6905 | 0.6332 |
2 | approved | online | RM | 0.4555 | 0.4987 | 0.5616 |