比较列行明智的部分字符串匹配

时间:2018-07-17 22:54:27

标签: python python-3.x pandas

我的问题与此类似: How to check whether the content of Column A is contained in Column B using Python DataFrame?

不幸的是,在我的情况下,选择的答案导致无类型错误。

我有以下格式的pandas数据框:

id,text_1,text_2_compare
1,yyy,yy
2,yxy,xx
3,zzy,zy
4,zzy,x
5,xyx,yx

我想比较这些列以查看“ text_1”中是否包含“ text_2_compare”并创建一个新指标。

id,text_1,text_2_compare,match
1,yyy,yy,1
2,yxy,xx,0
3,zzy,zy,1
4,zzy,x,0
5,xyx,yx,1

任何技巧或窍门(尤其是矢量化的实现方式)将不胜感激!

3 个答案:

答案 0 :(得分:1)

import re

df['compare_match']=df.apply(lambda v:len(re.findall(v[2],v[1])),axis=1)

df
   id text_1 text_2_compare  compare_match
0   1    yyy             yy              1
1   2    yxy             xx              0
2   3    zzy             zy              1
3   4    zzy              x              0
4   5    xyx             yx              1

编辑:

我实际上认为OP需要text_2_compared出现在text_1中的次数,但是在再次阅读问题时,似乎OP只想要一个指标变量。因此,像上面@gaganso一样使用v[2] in v[1]就足够了

答案 1 :(得分:1)

以@Onyambu的答案为基础。

C:\code\practice\promise-exercise2>node index.js *********** begin *********** *********** end *********** working... 可以代替in

re.findall()

输出:

df["match"] = df.apply(lambda v: int(v[2] in v[1]),axis=1)
print(df["match"]

答案 2 :(得分:0)

使用简单列表

df['New']=[int(y in x) for x , y in zip(df['text_1'],df['text_2_compare'])]
df
Out[496]: 
   id text_1 text_2_compare  New
0   1    yyy             yy    1
1   2    yxy             xx    0
2   3    zzy             zy    1
3   4    zzy              x    0
4   5    xyx             yx    1
相关问题