[英]How to get cumulative sum of unique IDs with group by?
我對 python 和 Pandas 非常陌生,它在 Pandas 數據框上工作,看起來像
Date Time ID Weight
Jul-1 12:00 A 10
Jul-1 12:00 B 20
Jul-1 12:00 C 100
Jul-1 12:10 C 100
Jul-1 12:10 D 30
Jul-1 12:20 C 100
Jul-1 12:20 D 30
Jul-1 12:30 A 10
Jul-1 12:40 E 40
Jul-1 12:50 F 50
Jul-1 1:00 A 40
我正在嘗試按日期、時間和 id 實現分組並應用累積總和,這樣如果下一個時間段中存在 id,則權重僅添加一次(唯一)。 結果數據框看起來像這樣
Date Time Weight
Jul-1 12:00 130 (10+20+100)
Jul-1 12:10 160 (10+20+100+30)
Jul-1 12:20 160 (10+20+100+30)
Jul-1 12:30 160 (10+20+100+30)
Jul-1 12:40 200 (10+20+100+30+40)
Jul-1 12:50 250 (10+20+100+30+40+50)
Jul-1 01:00 250 (10+20+100+30+40+50)
這是我在下面嘗試過的,但是這仍然多次計算重量:
df=df.groupby(['date','time','ID'])['Wt'].apply(lambda x: x.unique().sum()).reset_index()
df['cumWt']=df['Wt'].cumsum()
任何幫助將非常感激!
非常感謝提前!
下面的代碼使用pandas.duplicate() 、 pandas.merge() 、 pandas.groupby/sum和pandas.cumsum()來獲得所需的輸出:
# creates a series of weights to be considered and rename it to merge
unique_weights = df['weight'][~df.duplicated(['weight'])]
unique_weights.rename('consider_cum', inplace = True)
# merges the series to the original dataframe and replace the ignored values by 0
df = df.merge(unique_weights.to_frame(), how = 'left', left_index=True, right_index=True)
df.consider_cum = df.consider_cum.fillna(0)
# sums grouping by date and time
df = df.groupby(['date', 'time']).sum().reset_index()
# create the cumulative sum column and present the output
df['weight_cumsum'] = df['consider_cum'].cumsum()
df[['date', 'time', 'weight_cumsum']]
產生以下輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.