![](/img/trans.png)
[英]Pandas create new column in df2 from another df1 column2 if a value in df1 column1 matches value in a list
[英]Create new col4 in df1 with a value1, if the single column in df2 contains the value2 from a column in df1
df1 例如是
col1 | col2 | col3 |
---|---|---|
abcdef | 吉克爾 | mnopqr |
abcdef1 | ghijkl1 | mnopqr1 |
df2 是
col1 |
---|
ghijkl1 |
本質上,如果 df1col2 中的值出現在 df2col1 中,我想將 col4 添加到值為“MM”的 df1
最終的 df1 將是:
col1 | col2 | col3 | col4 |
---|---|---|---|
abcdef | 吉克爾 | mnopqr | |
abcdef1 | ghijkl1 | mnopqr1 | 毫米 |
使用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.