python - pandas dataframe sum 与 groupby

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

我有一个 pandas 数据框,其结构如下:

[
    ['x', '1', '-7']
    ['x', '2', '-2']
    ['y', '3', '-1']
    ['y', '4', '-3']
]

我必须对第一列(值为 xys)进行分组,并找到每个 x 第二列和第三列的总和code> 和 y 像这样:

[
    ['x', 3, -9]
    ['y', 7, -4]
]

如何使用 pandas 做到这一点?

最佳答案

设置
我将您的字符串数字转换为实际数字

df = pd.DataFrame(
    [
        ['x', '1', '-7'],
        ['x', '2', '-2'],
        ['y', '3', '-1'],
        ['y', '4', '-3']
    ]
)

df[1] = pd.to_numeric(df[1])
df[2] = pd.to_numeric(df[2])

解决方案

df.groupby(0).sum()

enter image description here

关于python - pandas dataframe sum 与 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40826979/

相关文章:

python - 自定义 argparse 帮助消息

python - 缺失值在 conti var 中替换为 med/mean,在 pandas dataframe 中替换为 categorical var 中的模式 - 按列对数据进行分组后)

python - 使用 Python 实现 collat​​z 函数

python-3.x - 如何使用 Python 3 处理 utf-8 文本?

python - 通过键数组访问字典,或将键初始化为子字典

python - python 中有孔的三角测量

python - 显示列表中的每个元素

python - 从列表和其他单个值创建 numpy 数组的最佳方法

python - dict.viewkeys() 返回的数据类型是什么? [ python 2.7 ]

Python 3 : Crash with free(): corrupted unsorted chunks while reading file