[英]Column value from first df to another df based on condition
I have original df where I have column "average", where is average value counted for country.我有原始 df,其中有“平均”列,其中计算国家/地区的平均值。 Now I have new_df, where I want to add these df average values based on country.
现在我有了 new_df,我想在其中添加基于国家/地区的这些 df 平均值。
df
id country value average
1 USA 3 2
2 UK 5 5
3 France 2 2
4 USA 1 2
new df
country average
USA 2
Italy Nan
I had a solution that worked but there is a problem, when there is in new_df a country for which I have not count the average yet.我有一个有效的解决方案但是有一个问题,当在 new_df 中有一个我还没有计算平均值的国家时。 In that case I want to fill just nan.
在那种情况下,我只想填写 nan。
Can you please recommend me any solution?你能给我推荐任何解决方案吗?
Thanks谢谢
If need add average
column to df2 use DataFrame.merge
with DataFrame.drop_duplicates
:如果需要将
average
列添加到 df2,请使用DataFrame.merge
和DataFrame.drop_duplicates
:
df2.merge(df1.drop_duplicates('country')[['country','average']], on='country', how='left')
If need aggregate mean
:如果需要汇总
mean
:
df2.join(df1.groupby('country')['average'].mean(), on='country')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.