简体   繁体   English

如果 df2 中的单个列包含来自 df1 中的列的 value2,则在 df1 中创建具有 value1 的新 col4

[英]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 col1 col2 col2 col3 col3
abcdef abcdef ghijkl吉克尔 mnopqr mnopqr
abcdef1 abcdef1 ghijkl1 ghijkl1 mnopqr1 mnopqr1

df2 is df2 是

col1 col1
ghijkl1 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 col1 col2 col2 col3 col3 col4 col4
abcdef abcdef ghijkl吉克尔 mnopqr mnopqr
abcdef1 abcdef1 ghijkl1 ghijkl1 mnopqr1 mnopqr1 MM毫米

Use Series.isin and then chain .map to convert True to 'MM', and False to a NaN value.使用Series.isin然后链接.mapTrue转换为“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.

相关问题 如果 df1 column1 中的值与列表中的值匹配,Pandas 从另一个 df1 column2 在 df2 中创建新列 - Pandas create new column in df2 from another df1 column2 if a value in df1 column1 matches value in a list 如果列值不在 df2 列中,则获取 df1 的行 - Get row of df1 if column value not in column df2 Pandas:如果df1列的值在df2列的列表中,则加入 - Pandas: Join if value of df1 column is in list of df2 column 如果df2索引中的df1索引,熊猫会更新列值 - Pandas update column value if df1 index in df2 index Python - 检查df2列中是否存在df1列中的值 - Python - Check if a value in a df1 column is present in df2 column 根据 df2 中的条件查找 df1 中的列值 - Looking up column value in df1 based on criteria in df2 根据 df1 中的值在 df2 中保留一列 - Keep one column in df2 based on value in df1 新df列,即当前df1值除以df2值 - New df column that is current df1 value divided by df2 value 如何确定 df1 中 column1 的值包含在 df2 中的 column1 中(python) - How can I determine that the value of column1 in df1 contains in column1 in df2 (python) 根据 df1 中的列值查找 df2 中的相交值,并使用 df1 中的检索值创建一个新列(不匹配的列名) - Lookup intersecting values in df2 based on column values in df1 and create a new column with retrieved value in df1 (non matching column names)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM