大熊猫比较两列,只保留匹配的单词字符串

时间:2019-04-05 03:04:59

标签: python pandas dataframe lambda

我正在尝试将1个数据帧列中的单词或字符串与同一df中的另一列进行比较,并输出仅包含匹配单词的第3列。

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:字符串索引必须为整数

3 个答案:

答案 0 :(得分:1)

使用apply' '.join,然后使用列表推导来获取匹配的值

此外,您必须使用axis=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

如果您想要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    NULL
2    chicken
dtype: object

答案 1 :(得分:0)

检查

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

答案 2 :(得分:0)

这里不需要使用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]