Python 熊猫部分字符串匹配,与contains相反

Python 熊猫部分字符串匹配,与contains相反,python,string,pandas,lookup,Python,String,Pandas,Lookup,我有两个数据帧,我想进行查找,根据部分字符串匹配将一列值从一个数据帧添加到另一个数据帧。(在我的真实案例中,有多个列用于匹配适当的行。)第一个数据帧是: idx name age 0 Anne 30 1 Bob 31 2 Chuck 32 第二个是 idx sex comment 0 M 'Bob is great!' 1 F 'Way to go Anne!' 2

我有两个数据帧,我想进行查找,根据部分字符串匹配将一列值从一个数据帧添加到另一个数据帧。(在我的真实案例中,有多个列用于匹配适当的行。)第一个数据帧是:

idx   name        age
0     Anne        30
1     Bob         31
2     Chuck       32
第二个是

idx   sex    comment
0     M      'Bob is great!'
1     F      'Way to go Anne!'
2     M      'Woodchuck'
我想将年龄列添加到第二个数据框中,使用注释字符串包含员工姓名的值。也就是说,查找df1的行,其中名称列中的字符串包含在来自df2['comment']的引用字符串中

但这是
str.contains()
函数的反向。在这种情况下,我需要一个“is in”函数,如:

df2['age'] = df2.apply(lambda row: df1['name'].str.isin(row['comment']), axis=1)
但熊猫似乎没有这个。最终结果应该是

idx   sex    comment             age
0     M      'Bob is great!'     31
1     F      'Way to go Anne!'   30
2     M      'Woodchuck'         32
如何实现对熊猫系列中的部分字符串的反向查找


(如果有关系,实际字符串是日语字符)

您可以使用str.contains,这将导致如下结果:

import pandas as pd
import numpy as np
#Create the column in the target dataframe
df2['age'] = pd.Series(np.NaN,index=df2.index)

for index,row in df1.iterrows():
    df2.loc[(df2['comment'].str.contains(row['name'])).fillna(False),'age'] = row['age'] 
这将使df2中所有在df1中包含名称的行具有相应的年龄

要添加多个条件,可以使用:

mask = (condition1) & (condition2)
df2.loc[mask,'age'] = row['age']