如何汇总每个州的“number”列中的值,然后根据“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
最佳答案
使用变换
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
关于python - 如何聚合两列中的值并从中创建一个新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44381192/