亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在CSV文件中對多個列進行分組和求和?

如何在CSV文件中對多個列進行分組和求和?

RISEBY 2022-08-02 18:16:07
我對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有人能幫忙嗎?到目前為止,我正在嘗試以下方法,但它對我不起作用。是否可以添加到以下代碼的第一行?還是我一開始就完全錯了?謝謝!groupbydf = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()df.to_csv(r'path/to/myfile_sum.csv')
查看完整描述

3 回答

?
慕雪6442864

TA貢獻1812條經驗 獲得超5個贊

你可以做一些手動:agg


(df.groupby('id', as_index=False)

   .agg({'date':'max', 'name':'first',

         'unitCount':'sum',

         'orderCount':'sum',

         'invoiceCount':'sum'})

   .to_csv('file.csv')

)


查看完整回答
反對 回復 2022-08-02
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

您可以執行以下操作


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


查看完整回答
反對 回復 2022-08-02
?
浮云間

TA貢獻1829條經驗 獲得超4個贊

您只需要調用對象,然后相應地重命名列名,最后將生成的數據幀寫入文件。sum()groupbycsv


以下操作應該可以解決問題:


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=';')


查看完整回答
反對 回復 2022-08-02
  • 3 回答
  • 0 關注
  • 242 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號