我正在尝试生成在company2中包含df中company1的所有行。我这样做:
df1=df[['company1','company2']][(df.apply(lambda x: x['company1'] in x['company2'], axis=1) == True)]
当我运行上面的代码行时,它还显示“South”与“Southern”匹配。此外,“南方”与“南方路线”相匹配。我想摆脱所有这些情况。 Company1只应包含在Company2的开头。并且,company1不应该成为company2中某些词的一部分,例如“South”(company1)与“Southern”(company2)相匹配。我应该如何修改我的代码以完成上述两个要求?
答案 0 :(得分:1)
我认为你需要:
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