[英]Merging of pandas dataframe with calculations
我有幾個熊貓數據框。
東風答:
ID | 日期 | 平均 | 數數 |
---|---|---|---|
1 | 27/06/2021 | 10 | 5 |
1 | 28/06/2021 | 12 | 4 |
東風乙:
ID | 日期 | 平均 | 數數 |
---|---|---|---|
1 | 27/06/2021 | 8 | 5 |
1 | 28/06/2021 | 6 | 6 |
1 | 29/06/2021 | 11 | 10 |
2 | 27/06/2021 | 3 | 10 |
2 | 28/06/2021 | 3 | 10 |
基本上,這些是從各種大數據源聚合的中間表的簡化。 如何合並這些數據框,以便 id+date 的平均值是正確的(即它是 (avg1 * count1 + avg2 * count2)/(count1 + count2))
以上兩個的預期DF應該是這樣的:
ID | 日期 | 平均 | 數數 |
---|---|---|---|
1 | 27/06/2021 | 9 | 10 |
1 | 28/06/2021 | 8.4 | 10 |
1 | 29/06/2021 | 11 | 10 |
2 | 27/06/2021 | 3 | 10 |
2 | 28/06/2021 | 3 | 10 |
謝謝。
你可以做
s = pd.concat([df1,df2])
cnt = s.groupby(['id','date'])['count'].sum()
amount = (s['avg']*s['count']).groupby([s['id'],s['date']]).sum()/cnt
amount.name='avg'
out = pd.concat([cnt,amount],axis=1).reset_index()
out
Out[34]:
id date count avg
0 1 27/06/2021 10 9.0
1 1 28/06/2021 10 8.4
2 1 29/06/2021 10 11.0
3 2 27/06/2021 10 3.0
4 2 28/06/2021 10 3.0
其他方式:
out=df1.merge(df2,on=['id','date'],suffixes=('_1','_2'),how='left'))
現在做計算:
out['avg']=out.eval("(avg_1*count_1+avg_2*count_2)/(count_1+count_2)")
out['count']=out.eval("count_1+count_2")
out=out.drop(out.filter(like='_').columns,1)
最后:
df2.update(out)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.