Python 熊猫比较两列,只保留匹配的字串

Python 熊猫比较两列,只保留匹配的字串,python,pandas,dataframe,lambda,Python,Pandas,Dataframe,Lambda,我试图将一个dataframe列中的单词或Sting与同一df中的另一列进行比较,并输出第三列,其中只包含匹配的单词 input Col1 the cat crossed a road the dog barked the chicken barked Col2 the cat alligator some words here chicken soup desired result Col3 the cat NULL chicken 这就是我所拥有的,但却得到了一个错误 df[Col3]

我试图将一个dataframe列中的单词或Sting与同一df中的另一列进行比较,并输出第三列,其中只包含匹配的单词

input
Col1
the cat crossed a road
the dog barked
the chicken barked

Col2
the cat alligator
some words here
chicken soup

desired result
Col3
the cat
NULL
chicken
这就是我所拥有的,但却得到了一个错误

df[Col3] = df[Col1].apply(lambda x: ' '.join([word for word in x.split() if word in x[Col2].split(' ')]))
错误是
TypeError:字符串索引必须是整数

使用
应用
,带有
''。连接
,然后使用列表理解来获取匹配的值

此外,必须使用轴=1才能使其工作:

print(df.apply(lambda x: ' '.join([i for i in x['Col1'].split() if i in x['Col2'].split()]), axis=1))
输出:

0    the cat
1           
2    chicken
dtype: object
0    the cat
1    NULL
2    chicken
dtype: object
如果希望
NULL
,而不仅仅是空值,请使用:

print(df.apply(lambda x: ' '.join([i for i in x['Col1'].split() if i in x['Col2'].split()]), axis=1).str.replace('', 'NULL'))
输出:

0    the cat
1           
2    chicken
dtype: object
0    the cat
1    NULL
2    chicken
dtype: object
核对

l=[' '.join([t for t in x if t in y]) for x, y in zip(df1.Col1.str.split(' '),df2.Col2.str.split(' '))]
pd.DataFrame({'Col3':l})
Out[695]: 
      Col3
0  the cat
1         
2  chicken

这里不需要使用lambda函数,只需检查每个单词是否包含在同一列的字符串中。zip()函数对于列迭代非常有用。以下是一种方法:

import pandas as pd

data_frame = pd.DataFrame(
    {'col1':{
        1:'the cat crossed a road',
        2:'the dog barked',
        3:'the chicken barked',},
    'col2':{
        1: 'the cat alligator',
        2: 'some words here',
        3: 'chicken soup'}}
)

# output the overlap as a list
output = [
    [word for word in line1.split() if word in line2.split()] 
    for line1, line2 in zip(data_frame['col1'].values, data_frame['col2'].values)
]

# To add your new values a column
data_frame['col3'] = output

# Or, if desired, keep as a list and remove empty rows 
output = [row for row in output if row]