Pandas:从一列的子字符串中提取首字母缩略词,并将其与另一列进行条件匹配

2024-05-29 03:18:33 发布

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

我试图匹配同一数据帧中两列中的名称,如果一列中的名称是另一列的首字母缩略词,即使它们包含相同的首字母缩略词子字符串,我希望创建一个函数来返回True

pd.DataFrame([['Global Workers Company gwc', 'gwc'], ['YTU', 'your team united']] , columns=['Name1','Name2'])

期望输出:

         Name1                      Name2               Match
0   Global Workers Company gwc           gwc            True
1   YTU                             your team united    True

我已经创建了一个lambda函数来只获取首字母缩写词,但还不能这样做

t = 'Global Workers Company gwc'
[x[0] for x in t.split()]

['G', 'W', 'C', 'g']

"".join(word[0][0] for word in test1.Name2.str.split()).upper()

Tags: 函数名称trueyourglobalcompanyteamunited
2条回答

您可以使用Dataframe.apply函数和axis=1参数在数据帧上应用自定义func。然后可以使用正则表达式将acronym与相应的大名或短语进行比较

试试这个:

import re

def func(x):
    s1 = x["Name1"]
    s2 = x["Name2"]

    acronym = s1 if len(s1) < len(s2) else s2
    fullform = s2 if len(s1) < len(s2) else s1

    fmtstr = ""
    for a in acronym:
        fmtstr += (r"\b" + a + r".*?\b")

    if re.search(fmtstr, fullform, flags=re.IGNORECASE):
        return True
    else:
        return False


df["Match"] = df.apply(func, axis=1)
print(df)

输出:

                        Name1             Name2  Match
0  Global Workers Company gwc               gwc   True
1                         YTU  your team united   True

我将使用地图绘制器。我们将有一个查找字典,它将数据转换为我们可以检查是否相等的相同类型

import pandas as pd

#data
df = pd.DataFrame([['Global Workers Company', 'gwc'], ['YTU', 'your team united']] , columns=['Name1','Name2'])


# create a mapper
mapper = {'gwc':'Global Workers Company',
          'YTU': 'your team united'}

def replacer(value, mapper=mapper):
     '''Takes in value and finds its map, 
        if not found return original value
     '''
    return mapper.get(value, value)

# create column checker and assign the equality 
df.assign(
    checker = lambda column: column['Name1'].map(replacer) == column['Name2'].map(replacer)
)

print(df)

相关问题 更多 >

    热门问题