繁体   English   中英

如何根据公共列将 dataframe 的列值替换为另一个 dataframe 的值?

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

我有两个数据框,一个看起来像这样:

hec_df:

事故年 因素 年龄
2007年 1.5 13
2008年 1.6 11
2009 1.7 15

和 hec_ldfs:

事故年 因素
2007年 1.6
2008年 1.64
2009 1.7

我的目标是用 df2 的因子值替换 df1 的因子值。 我的代码是

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

但它在因子列上返回 NaN。 有谁知道为什么会这样?

编辑:我不确定为什么我的第一个 dataframe 是这样格式化的,有人知道如何解决吗?

您将 factor 映射到 accident_year,而不是 hec_df.accident_year 到 hec_df.accident 年份

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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