Pandas:使用fuzzyfuzzy匹配字符串并检索其他列的值

2024-05-23 21:59:43 发布

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

我有一个数据帧df,如下所示

33KV Feeder      11KV Feeder     Circle_name          Codes
Shree Gopal                         SPS            33ShreeGopal_DPS
                  Jai Balaji        LRS            Jai_Balajilaji_LRS
Mithapur-1                          SPS            33Mithapur-1_SPS
                  Coal Board No. 2  LRS            Coal_Board_2_LRS
Mithapur-2                          DPS            33Mithapur-2_DPS

目标:我想在33KV Feeder11KV Feeder中匹配用户输入(馈线名称和圆圈名称),然后在Codes中检索值。例如,如果用户以MithapurSPS的形式提供输入,那么逻辑应该检索33KV Mithapur-1_SPS。如果用户提供Coal Board作为feeder名称和LRS,那么它应该选择Coal Board o. 2_LRS

到目前为止,我所尝试的:

import pandas as pd
from fuzzywuzzy import fuzz,process
df = pd.read_csv(file_path,encoding="ISO-8859-1")
feeder_input = input() # Lets say Mithapur
circle_input = input() # Lets say SPS
match_feeder = process.extract(feeder_input,data['11KV Feeder'],scorer=fuzz.token_sort_ratio)
match_circle = process.extract(feeder_input,data['Circle name'],scorer=fuzz.token_sort_ratio)
if match_feeder[0][1] > 60 match_circle[0][1] > 90:
      z = df.loc[data[['11Kv Feeder','33Kv Feeder']].str.contains(match_feeder[0][0]).any(1) & df['Circle_name'].str.contains(match_circle[0][0]),['Codes']].iloc[0]
      print(z)

上面的代码抛出一个错误:

AttributeError: 'DataFrame' object has no attribute 'str'

我将z更改如下

z=data.loc[data[['11Kv Feeder','33Kv Feeder']].eq(match_feeder[0][0]).any(1) & data['Circle_name'].str.contains(match_circle[0][0]),['Codes']]

结果是抛出一个空数据帧。相反,我应该得到33KV Mithapur-1_SPS作为z的值

如果我从上面删除match_circle,那么我会得到以下输出

Mithapur-1_SPS
Mithapur-2_DPS 

现在我的问题是如何有效地包含两个输入并检索正确的Codes?我在哪里遗漏了上述代码


Tags: namedfinputdatamatchcodesspscircle
1条回答
网友
1楼 · 发布于 2024-05-23 21:59:43

好的,我已经找到了一个解决方案。我刚刚对match_feeder进行了如下调整

match_feeder = process.extractOne(feeder_input,data['Name of the 11Kv Feeder'],scorer=fuzz.token_sort_ratio)

if语句启动时,我还更改了以下内容:

if (match_feeder[1] > 60) and (match_circle[0][1] > 90):
    z = df.loc[data[['11Kv Feeder','33Kv Feeder']].eq(match_feeder[0]).any(1) & data['Circle Name'].str.contains(match_circle[0][0]),['Codes']].iloc[0]
    print(z)

我希望上述问题及其解决方案可能对其他人有用

相关问题 更多 >