Reputation: 628
How can I sum up the values in column "number" for each state and then create a new column from those values next to "number"?
So far I have this to aggregate:
out_state_total['df']=df.groupby('State')['out-of-state'].sum(axis=1)
But for some reason I can't create a new column from those values...
example state in-state out-of-state final_state
red NJ 3000 99 AL
blue ND 43 500 AK
green NY 8000 10 AZ
gray NJ 94 20 AR
orange DE 32 7
Upvotes: 1
Views: 432
Reputation: 38415
Use Transform
df[['in_state_total','out_state_total']]=df.groupby('state')['in-state', 'out-of-state'].transform('sum')
example state in-state out-of-state in_state_total out_state_total
0 red NJ 3000 99 3094 119
1 blue ND 43 500 43 500
2 green NY 8000 10 8000 10
3 gray NJ 94 20 3094 119
4 orange DE 32 7 32 7
Upvotes: 1