简体   繁体   中英

How do I replace column values of a dataframe with values of another dataframe based on a common column?

I have two dataframes, one that looks like this:

hec_df:

accident year factor age
2007 1.5 13
2008 1.6 11
2009 1.7 15

and hec_ldfs:

accident year factor
2007 1.6
2008 1.64
2009 1.7

My goal is to replace the factor value of df1 with the factor value of df2. My code for this is

hec_df['factor'] = hec_df['factor'].map(hec_ldfs.set_index('accident year')['factor'])

But it returns NaN on the factor column. Does anyone know why this is happening?

EDIT: I'm not sure why my first dataframe is formatted like that, does anyone know how to fix it?

you're mapping factor to the accident_year, instead of hec_df.accident_year to the hec_df.accident year

hec_df['factor'] = hec_df['accident year'].map(hec_ldfs.set_index('accident year')['factor']).fillna(hec_df['factor'])
hec_df
accident year   factor  age
0   2007    1.60    13
1   2008    1.64    11
2   2009    1.70    15

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