簡體   English   中英

Pandas 聚合 groupby 以獲得特定值

[英]Pandas aggregate groupby for specific values

如果我有下表,

ID#    dispute_amt   year   month
1234   12.50         2019   3
1234   4.00          2019   3
5678   100           2020   5

我希望所需的表如下

ID#    dispute_count dispute_amt   year   month
1234   2             16            2019   3
5678   1             100           2020   5

頂部的當前表具有重復的 ID#,每月/每年有多次爭議。 我想將其匯總到唯一的 ID# 中,然后能夠計算每個月/年每個 ID# 的所有爭議。 我想我需要在這里使用某種 groupby 運算符,但我不知道如何使用 python/pandas 實際執行此操作。

這里的任何幫助都會很棒!

使用groupby().agg()

 df.groupby(['ID#', 'year', 'month']).agg(dispute_count =('dispute_amt','count')\
,dispute_amt=('dispute_amt','sum')).reset_index()

    ID#  year  month  dispute_count  dispute_amt
0  1234  2019      3              2         16.5
1  5678  2020      5              1        100.0

既然你寫了你想每年每月聚合 ID,你可以 yse groupby ID 並重置索引

 df
 .groupby(['ID#','year','month')['dispute_amt']
 .count().reset_index(name='dispute_count')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM