账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    pandas的DataFrame多行求和问题.
    29
    0

    开发环境

    python 3.6
    pandas 0.23.3

    有一个DataFrame,如下表示:

    import pandas as pd
    arr = [[10,10,1],[22,24.2,1.1],[15,15,1],[9,8.1,0.9],[50,55,1.1]]
    df = pd.DataFrame(arr,columns=['volume','amount','price'])
        volume  amount  price
    0      10    10.0    1.0
    1      22    24.2    1.1
    2      15    15.0    1.0
    3       9     8.1    0.9
    4      50    55.0    1.1

    需要volume列每行累加的和,得出total列

        volume  amount  price  total
    0      10    10.0    1.0    10.0
    1      22    24.2    1.1    32.0
    2      15    15.0    1.0    47.0
    3       9     8.1    0.9    56.0
    4      50    55.0    1.1    106.0

    目前我的写法:

    for index in df.index:
         num = df[df.index < index]['volume'].sum()
         df.loc['total'] = num

    求助各位大神,有没有更好的方法?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 惆怅的一颗心 普通会员 1楼

      在pandas中,可以使用groupbysum函数来实现DataFrame的多行求和。假设你有一个DataFrame,其中每一行都包含一个数值,你想求和每一行的数值之和,你可以使用以下代码:

      ```python import pandas as pd

      假设df是你的DataFrame

      df = pd.DataFrame({ 'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B': [1, 2, 3, 4, 5, 6, 7, 8], 'C': [10, 20, 30, 40, 50, 60, 70, 80] })

      求和每一行的数值之和

      total_sum = df.groupby('A')['B'].sum()

      print(total_sum) ```

      在这个例子中,我们首先导入了pandas库,然后定义了一个DataFramedf。然后,我们使用groupby函数将DataFrame分组为每个'A'的行,然后使用sum函数求和每一行的数值之和。最后,我们打印出结果。

      注意,groupby函数将DataFrame按'A'的行分组,然后对每一组应用一个函数(在这个例子中是求和)。sum函数返回的是每一组的数值之和。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部