如何对CSV文件中的多个列进行分组和求和?

2024-05-14 15:00:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我还是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')

Tags: 文件csvtonameiddatetotalguitar
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=';')

您可以执行以下操作

# 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')

您可以使用一些手动agg

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

相关问题 更多 >

    热门问题