[英]Create new col4 in df1 with a value1, if the single column in df2 contains the value2 from a column in df1
df1 for example is df1 例如是
col1 ![]() |
col2 ![]() |
col3 ![]() |
---|---|---|
abcdef ![]() |
ghijkl![]() |
mnopqr ![]() |
abcdef1 ![]() |
ghijkl1 ![]() |
mnopqr1 ![]() |
df2 is df2 是
col1 ![]() |
---|
ghijkl1 ![]() |
essentially I want to add a col4 to df1 with the value "MM" if the value in df1col2 appears in df2col1本质上,如果 df1col2 中的值出现在 df2col1 中,我想将 col4 添加到值为“MM”的 df1
the final df1 would be:最终的 df1 将是:
col1 ![]() |
col2 ![]() |
col3 ![]() |
col4 ![]() |
---|---|---|---|
abcdef ![]() |
ghijkl![]() |
mnopqr ![]() |
|
abcdef1 ![]() |
ghijkl1 ![]() |
mnopqr1 ![]() |
MM![]() |
Use Series.isin
and then chain .map
to convert True
to 'MM', and False
to a NaN value.使用
Series.isin
然后链接.map
将True
转换为“MM”,将False
转换为 NaN 值。
df1['col4'] = df1['col2'].isin(df2['col1']).map({True:'MM',False:np.nan})
print(df1)
col1 col2 col3 col4
0 abcdef ghijkl mnopqr NaN
1 abcdef1 ghijkl1 mnopqr1 MM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.