python - 如何聚合两列中的值并从中创建一个新列?

标签 python python-2.7 python-3.x pandas

如何汇总每个州的“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/

相关文章:

python - PyQt。如何在 QTableView 中插入小部件

python - 子类不识别父类的模块导入?

python - 如何在 python 类上创建带参数的装饰函数?

python - 'pick_event' 处理程序未拾取 Matplotlib 行

python - python 库中的 "non-integer arg 1 for randrange()"

python - 在Opencv中将图像与深度图对齐

python - 将比较结果作为pandas.DataFrame的索引

python - 对矩阵中的第一列和第二个列表执行 "AND"操作

python - fnmatch 不适用于变量,但适用于静态字符串

python - 读取 json 时替代 eval