简体   繁体   中英

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. Now I have new_df, where I want to add these df average values based on country.

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. In that case I want to fill just nan.

Can you please recommend me any solution?

Thanks

If need add average column to df2 use DataFrame.merge with DataFrame.drop_duplicates :

df2.merge(df1.drop_duplicates('country')[['country','average']], on='country', how='left')

If need aggregate mean :

df2.join(df1.groupby('country')['average'].mean(), on='country')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM