Python 首先,检查一列是否包含来自另一列的字符,并标记该字符?;

Python 首先,检查一列是否包含来自另一列的字符,并标记该字符?;,python,pandas,dataframe,Python,Pandas,Dataframe,有两个数据帧,df1和df2。e、 g df1=pd.DataFrame({'index':[1,2,3,4], 'col1':['12abc12','12abcbla','abc','jh']}) df2=pd.DataFrame({'col2':['abc','efj']}) 我想要的是这样的(从df2中找到包含字符的所有行,并将它们标记出来) 我找到了一份工作,但不完全是我想要的。Thx用于任何提前的想法。如果需要,使用第一个匹配值: df1['new'] = df1['col1'].s

有两个数据帧,df1和df2。e、 g

df1=pd.DataFrame({'index':[1,2,3,4],
'col1':['12abc12','12abcbla','abc','jh']})
df2=pd.DataFrame({'col2':['abc','efj']})
我想要的是这样的(从
df2
中找到包含字符的所有行,并将它们标记出来)

我找到了一份工作,但不完全是我想要的。Thx用于任何提前的想法。

如果需要,使用第一个匹配值:

df1['new'] = df1['col1'].str.extract(f'({"|".join(df2["col2"])})', expand=False).fillna('')
print (df1)
   index      col1  new
0      1   12abc12  abc
1      2  12abcbla  abc
2      3       abc  abc
3      4        jh     
如果需要所有匹配值,请使用和:

df1['new'] = df1['col1'].str.extract(f'({"|".join(df2["col2"])})', expand=False).fillna('')
print (df1)
   index      col1  new
0      1   12abc12  abc
1      2  12abcbla  abc
2      3       abc  abc
3      4        jh     
df1 = pd.DataFrame({'index': [1, 2, 3, 4],
                    'col1': ['12abc1defj2', '12abcbla', 'abc', 'jh']})

df2 = pd.DataFrame({'col2': ['abc', 'efj']})

df1['new'] = df1['col1'].str.findall("|".join(df2["col2"])).str.join(',')
print (df1)
   index         col1      new
0      1  12abc1defj2  abc,efj
1      2     12abcbla      abc
2      3          abc      abc
3      4           jh