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

2024-06-28 20:55:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将1个数据帧列中的单词或stings与同一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

这是我所拥有的,只是有一个错误。在

^{pr2}$

错误是 TypeError:字符串索引必须是整数


Tags: the数据dfinput错误单词catcol2
3条回答

{{than{1>使用{cd2>来匹配}列表

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

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

输出:

^{pr2}$

如果您想要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

检查

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]

相关问题 更多 >