按行比较列以获得部分字符串匹配

2024-09-28 03:20:32 发布

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

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

不幸的是,在我的例子中,选择的答案导致了一个非类型错误。你知道吗

我有一个熊猫数据帧,格式如下:

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

我想比较这些列,看看“text\u 1”中是否包含“text\u 2\u 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

任何提示或技巧(特别是矢量化的实现)将不胜感激!你知道吗


Tags: totextidcheckcolumnhowcomparexx
3条回答

基于@onyanbu的答案。你知道吗

in可以用来代替re.findall()

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

输出:

0    1
1    0
2    1
3    0
4    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]就足够了

使用简单列表

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

相关问题 更多 >

    热门问题