[英]Pandas: finding mean in the dataframe based on condition included in another
我有兩個數據框,如下所示。
數據框1:
國家 | 類型 | 開始周 | end_week |
---|---|---|---|
1 | 一個 | 12 | 13 |
2 | b | 13 | 14 |
數據框2:
國家 | 類型 | 星期 | 價值 |
---|---|---|---|
1 | 一個 | 12 | 1000 |
1 | 一個 | 13 | 900 |
1 | 一個 | 14 | 800 |
2 | b | 12 | 1000 |
2 | b | 13 | 900 |
2 | b | 14 | 800 |
我想將第二個 dataframe 的平均值添加到第一個 dataframe 列中,並在 start_week 和 end_week 之間。
我希望所需的 output 如下所示:
國家 | 類型 | 開始周 | end_week | 平均 |
---|---|---|---|---|
1 | 一個 | 12 | 13 | 950 |
2 | b | 13 | 14 | 850 |
這是一種方法:
combined = df1.merge(df2 , on =['country','type'])
combined = combined.loc[(combined.start_week <= combined.week) & (combined.week <= combined.end_week)]
output = combined.groupby(['country','type','start_week','end_week'])['value'].mean().reset_index()
output:
>>
country type start_week end_week value
0 1 a 12 13 950.0
1 2 b 13 14 850.0
您可以使用 pd.melt 和 numpy arrays 進行比較。
# melt df1
melted_df1 = df1.melt(id_vars=['country','type'],value_name='week')[['country','type','week']]
# for loop to compare two dataframe arrays
result = []
for i in df2.values:
for j in melted_df1.values:
if (j == i[:3]).all():
result.append(i)
break
# Computing mean of the result dataframe
result_df = pd.DataFrame(result,columns=df2.columns).groupby('type').mean().reset_index()['value']
# Assigning result_df to df1
df1['avg'] = result_df
country type start_week end_week avg
0 1 a 12 13 950.0
1 2 b 13 14 850.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.