【问题标题】:How can I group and sum multiple columns in CSV file?如何对 CSV 文件中的多个列进行分组和求和?
【发布时间】:2020-02-18 00:24:57
【问题描述】:

我还是 python 和 pandas 的新手,目前正在尝试获取 CSV 文件中多列的总和。

我有一个 CSV 文件,其中包含要对 unitCountorderCountinvoiceCount 求和的列:

     date       id   name   unitCount   orderCount   invoiceCount
 2020-02-12     1   Guitar     200          100           200
 2020-02-12     2   Drums      300          200           100
 2020-02-12     3   Piano      400          700           300
 2020-02-11     1   Guitar     100          500           300
 2020-02-11     2   Drums      200          400           400
 2020-02-11     3   Piano      300          300           100

我想要的输出是一个 CSV 文件,其中包含最后 3 列的总和(按 ID 分组)并仅链接到最新日期:

     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
 2020-02-12     1   Guitar        300              600                   500
 2020-02-12     2   Drums         500              600                   500
 2020-02-12     3   Piano         700              1000                  400

有人可以帮忙吗?

到目前为止,我一直在尝试以下方法,但它对我不起作用。可以将groupby 添加到以下代码的第一行吗?还是我一开始就完全错了?谢谢!

df = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()
df.to_csv(r'path/to/myfile_sum.csv')

【问题讨论】:

  • 你真的需要熊猫吗?因为它可以通过生成另一个带有计算总数的 CSV 文件来解决。

标签: python pandas csv math sum


【解决方案1】:

您可以手动操作agg

(df.groupby('id', as_index=False)
   .agg({'date':'max', 'name':'first',
         'unitCount':'sum',
         'orderCount':'sum',
         'invoiceCount':'sum'})
   .to_csv('file.csv')
)

【讨论】:

    【解决方案2】:

    您可以执行以下操作

    # group rows by 'id' column
    df.groupby('id', as_index=False).agg({'date':'max',
                                          'name':'first',
                                          'unitCount':'sum',
                                          'orderCount':'sum',
                                          'invoiceCount':'sum'}
    
    # change the order of the columns
    df = df[['date', 'id', 'name', 'unitCount', 'orderCount'  ,'invoiceCount']]
    
    # set the new column names
    df.columns=['date', 'id', 'name', 'total_unitCount', 'total_orderCount'  ,'total_invoiceCount']
    
    # save the dataframe as .csv file
    df.to_csv('path/to/myfile_sum.csv')
    

    【讨论】:

      【解决方案3】:

      您只需在groupby 对象上调用sum(),然后相应地重命名列名,最后将生成的数据框写入csv 文件。


      以下应该可以解决问题:

      df = pd.read_csv(r'path/to/myfile.csv', sep=';')
      
      df.groupby(['id', 'name'])['unitCount', 'orderCount', 'invoiceCount'] \
        .sum() \
        .rename(columns={'unitCount':'total_unitCount', 'orderCount' : 'total_orderCount', 'invoiceCount': 'total_invoiceCount'}) \
        .to_csv('path/to/myoutputfile_sum.csv', sep=';')
      

      【讨论】:

        猜你喜欢
        • 2015-05-17
        • 2018-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-23
        • 2023-04-02
        • 1970-01-01
        相关资源
        最近更新 更多