简体   繁体   English

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

[英]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: hec_df:

accident year事故年 factor因素 age年龄
2007 2007年 1.5 1.5 13 13
2008 2008年 1.6 1.6 11 11
2009 2009 1.7 1.7 15 15

and hec_ldfs:和 hec_ldfs:

accident year事故年 factor因素
2007 2007年 1.6 1.6
2008 2008年 1.64 1.64
2009 2009 1.7 1.7

My goal is to replace the factor value of df1 with the factor value of df2.我的目标是用 df2 的因子值替换 df1 的因子值。 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.但它在因子列上返回 NaN。 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?编辑:我不确定为什么我的第一个 dataframe 是这样格式化的,有人知道如何解决吗?

you're mapping factor to the accident_year, instead of hec_df.accident_year to the hec_df.accident year您将 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.

相关问题 如何使用另一个数据框添加数据框并基于列更新公共值 - how to add a dataframe with another dataframe and updated common values based on a column 如何用另一个数据框列切片中的值替换数据框列的切片? - How do I replace a slice of a dataframe column with values from another dataframe column slice? 如何用另一个 dataframe 的值替换 dataframe 列中的一组值? - how do i replace set of values in a dataframe column with values from another dataframe? 根据另一列的值替换Pandas数据框的Column的值 - Replace values of a Pandas dataframe's Column based on values of another column 根据python另一列中的公共值在数据框的一列中划分2个值 - Dividing 2 values in a column of dataframe based on common value in another column in python 如何根据公共值将数据框中列的值添加到另一个数据框中? 熊猫/蟒蛇 - how to add values of a column in dataframe to another dataframe based on common values? pandas/python 根据另一个 dataframe 中匹配的 id 替换 dataframe 列值 - Replace dataframe column values based on matching id in another dataframe 如何根据第二个 Dataframe 值的条件替换 Dataframe 列值 - How to Replace Dataframe Column Values Based on Condition of Second Dataframe Values 如何根据同一 dataframe 中另一列的值替换 Dataframe 中列中的 NaN 值 - How to replace NaN value in column in Dataframe based on values from another column in same dataframe 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM