我正在尝试生成 df 中的 company1 包含在 company2 中的所有行。我是这样做的:
df1=df[['company1','company2']][(df.apply(lambda x: x['company1'] in x['company2'], axis=1) == True)]
当我运行上面的代码行时,它还显示“South”与“Southern”相匹配。此外,“South”与“Route South”相匹配。我想摆脱所有这样的情况。 Company1 应该只包含在 Company2 的开头。并且,company1 不应该是 company2 中某个词的一部分,例如“South”(company1)与“Southern”(company2)相匹配。我应该如何修改我的代码来完成上述两个要求?
最佳答案
我认为你需要:
df = pd.DataFrame({'company1': {0: 'South', 1: 'South', 2:'South'},
'company2': {0: 'Southern', 1: 'Route South', 2: 'South Route'}})
print (df)
company1 company2
0 South Southern
1 South Route South
2 South South Route
df1=df[df['company2'].str.contains("|".join('^' + df['company1'] + ' '))]
print (df1)
company1 company2
2 South South Route
关于python - Pandas 中的字符串包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117685/