簡體   English   中英

Pandas:從一列的子字符串中提取首字母縮寫詞並將其與具有條件的另一列匹配

[英]Pandas: Extract acronym from substrings of one column and match it to another column with a condition

我正在嘗試匹配同一數據框中兩列中的名稱,如果一列中的名稱是另一列的首字母縮寫詞,即使它們包含相同的首字母縮略詞子字符串,我想創建一個函數以返回 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()

您可以使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM