如何总结列"数字"中的值?对于每个州,然后从" number"?
旁边的那些值创建一个新列到目前为止,我有这个聚合:
out_state_total['df']=df.groupby('State')['out-of-state'].sum(axis=1)
但由于某些原因,我无法从这些值中创建新列...
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
答案 0 :(得分:1)
使用转换
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