3 回答
TA贡献1851条经验 获得超4个赞
使用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
TA贡献1783条经验 获得超4个赞
这里不需要使用 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]
TA贡献1877条经验 获得超6个赞
检查
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
添加回答
举报