[英]Update values in pandas columns based on values from another DataFrame
Two DataFrames df1
and df2
both has Weight in lb columns if Weight in lb matches I need to update the corresponding BMI in df1 from df2.如果 lb 中的权重匹配,则两个 DataFrame
df1
和df2
都在 lb 列中具有权重,我需要从 df2 更新 df1 中的相应 BMI。
DataFrame df1
=数据帧
df1
=
Index![]() |
First Name![]() |
Age![]() |
Gender![]() |
Weight in lb![]() |
BMI![]() |
---|---|---|---|---|---|
0 ![]() |
James![]() |
21 ![]() |
Male![]() |
167 ![]() |
|
1 ![]() |
John![]() |
25 ![]() |
Male![]() |
175 ![]() |
|
2 ![]() |
Patricia![]() |
23 ![]() |
Female![]() |
132 ![]() |
|
4 ![]() |
Kevin![]() |
22 ![]() |
Male![]() |
169 ![]() |
|
5 ![]() |
Alex![]() |
27 ![]() |
Male![]() |
169 ![]() |
DataFrame df2
=数据帧
df2
=
Weight in lb![]() |
BMI![]() |
Height![]() |
---|---|---|
165 ![]() |
16.5 ![]() |
180 ![]() |
166 ![]() |
17.0 ![]() |
180 ![]() |
167 ![]() |
17.3 ![]() |
180 ![]() |
168 ![]() |
17.4 ![]() |
180 ![]() |
169 ![]() |
17.9 ![]() |
180 ![]() |
170 ![]() |
18.4 ![]() |
180 ![]() |
171 ![]() |
18.7 ![]() |
180 ![]() |
172 ![]() |
18.9 ![]() |
180 ![]() |
173 ![]() |
19.2 ![]() |
180 ![]() |
174 ![]() |
19.3 ![]() |
180 ![]() |
175 ![]() |
19.6 ![]() |
180 ![]() |
176 ![]() |
19.9 ![]() |
180 ![]() |
177 ![]() |
20.0 ![]() |
180 ![]() |
178 ![]() |
20.2 ![]() |
180 ![]() |
179 ![]() |
21.6 ![]() |
180 ![]() |
180 ![]() |
21.9 ![]() |
180 ![]() |
181 ![]() |
22.1 ![]() |
180 ![]() |
182 ![]() |
22.3 ![]() |
180 ![]() |
183 ![]() |
22.5 ![]() |
180 ![]() |
184 ![]() |
22.8 ![]() |
180 ![]() |
185 ![]() |
22.9 ![]() |
180 ![]() |
186 ![]() |
23.0 ![]() |
180 ![]() |
187 ![]() |
22.1 ![]() |
180 ![]() |
188 ![]() |
22.1 ![]() |
180 ![]() |
I tried我试过了
df1['BMI'] = df2.loc[df2['Weight in lb'].isin(df1['Weight in lb'],'BMI']
But it is not working, I cannot do merge operation because the original dataframe is too complex for that但它不起作用,我无法进行合并操作,因为原始数据框太复杂了
Desired Output df1
=所需输出
df1
=
Index![]() |
First Name![]() |
Age![]() |
Gender![]() |
Weight in lb![]() |
BMI![]() |
---|---|---|---|---|---|
0 ![]() |
James![]() |
21 ![]() |
Male![]() |
167 ![]() |
17.3 ![]() |
1 ![]() |
John![]() |
25 ![]() |
Male![]() |
175 ![]() |
19.6 ![]() |
2 ![]() |
Patricia![]() |
23 ![]() |
Female![]() |
132 ![]() |
|
4 ![]() |
Kevin![]() |
22 ![]() |
Male![]() |
169 ![]() |
17.9 ![]() |
5 ![]() |
Alex![]() |
27 ![]() |
Male![]() |
169 ![]() |
17.9 ![]() |
You can use df2 to make a mapping from weight to BMI and then use it on df1您可以使用 df2 进行从体重到 BMI 的映射,然后在 df1 上使用它
weight_to_bmi = dict(df2.values)
df1['BMI'] = df1['Weight in lb'].map(weight_to_bmi)
Building off of mitoRibo's Answer建立在 mitoRibo 的答案之上
weight_to_bmi = pd.Series(df2['Weight in lb'].values,index=df2['BMI']).to_dict()
df1['BMI'] = df1['Weight in lb'].map(weight_to_bmi)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.