[英]Assign values column based on a column in another dataframe
I would like to assign values to a column based on the values in another dataframe.我想根据另一个 dataframe 中的值将值分配给列。
For example, in the example below the values in column B of df2
should be equal to the df['B']
value in df1
where df1['A'] = df2['A']
.例如,在下面的示例中,
df2
的 B 列中的值应等于 df1 中的df['B']
值,其中df1
df1['A'] = df2['A']
。 The output should then be the same as df3
. output 应该与
df3
相同。
> import pandas as pd
> import numpy as np
>
> df1 = pd.DataFrame({'A':[1,2,3],'B':["req 1", "req 2","req 3"]})
> df2 = pd.DataFrame({'A':[2,1,7],'B':[np.nan,np.nan,np.nan]})
> df3= pd.DataFrame({'A':[2,1,7],'B':["req 2", "req 1",np.nan]})
Could somebody help me with this?有人可以帮我解决这个问题吗?
You can do merge to achieve this -您可以合并来实现这一点 -
df2 = df2.merge(df1, on='A', how='left').drop('B_x', axis=1).rename(columns={"B_y": 'B'})
output - output -
A B
0 2 req 2
1 1 req 1
2 7 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.