簡體   English   中英

如何從 dataframe 的多種可能性中找到最佳字符串匹配?

[英]How to find best string match out of multiple possibilities in a dataframe?

我有一個看起來像這樣的 DF:

    Row      Master                     Option1                  Option2
    1        00150042 plc               WAGON PLC                wegin llp
    2        01 telecom, ltd.           01 TELECOM LTD           telecom 1
    3        0404 investments limited   0404 Investments Ltd     404 Limited Investments

我想要做的是分別將option1option2列與主列進行比較,並為每個列獲得相似度分數。

我有提供分數的代碼:

    from difflib import SequenceMatcher

    def similar(a, b):
         return SequenceMatcher(None, a, b).ratio()

我需要幫助的是關於如何實現它的邏輯。

它是一個 for 循環,它將遍歷 Option1 和主列,將分數保存在名為 Option1_score 的新列中,然后對 Option2 列執行相同的操作嗎?

非常感謝任何幫助!

使用您提供的 dataframe:

import pandas as pd

df = pd.DataFrame(
    {
        "Row": [1, 2, 3],
        "Master": ["00150042 plc", "01 telecom, ltd.", "0404 investments limited"],
        "Option1": ["WAGON PLC", "01 TELECOM LTD", "0404 Investments Ltd"],
        "Option2": ["wegin llp", "telecom 1", "404 Limited Investments"],
    }
)

這是使用 Python f-strings和 Pandas apply的一種方法:

for col in ["Option1", "Option2"]:
    df[f"{col}_score(%)"] = df.apply(
        lambda x: round(similar(x["Master"], x[col]) * 100, 1), axis=1
    )

然后:

print(df)
# Output
   Row                    Master               Option1  \
0    1              00150042 plc             WAGON PLC   
1    2          01 telecom, ltd.        01 TELECOM LTD   
2    3  0404 investments limited  0404 Investments Ltd   

                   Option2  Option1_score(%)  Option2_score(%)  
0                wegin llp               9.5              19.0  
1                telecom 1              26.7              64.0  
2  404 Limited Investments              81.8              63.8 

暫無
暫無

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

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