gpt4 book ai didi

python - 在 pandas 数据框列中搜索特定的字符串集,然后搜索该字符串

转载 作者:行者123 更新时间:2023-12-02 02:24:56 24 4
gpt4 key购买 nike

我想在特定列中搜索一组值。如果发生匹配,则返回匹配的字符串。目前我只能得到 true 或 false 的回复。步骤如下:

  1. 创建 df:
Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4', np.nan],
'Price': [22000,25000,27000,35000, 29000],
'Liscence Plate': ['ABC 123', 'XYZ 789', 'CBA 321', 'ZYX 987', 'DEF 456']}

df = pd.DataFrame(Cars,columns= ['Brand', 'Price', 'Liscence Plate'])
  • 搜索特定值集:
  • search_for_these_values = ['Honda', 'Toy', 'Ford Focus', 'Audi A4 2019']
    pattern = '|'.join(search_for_these_values)
    df['Match'] = df["Brand"].str.contains(pattern, na=False)
  • 打印 df:
  • print(df)
    Brand Price Liscence Plate Match
    0 Honda Civic 22000 ABC 123 True
    1 Toyota Corolla 25000 XYZ 789 True
    2 Ford Focus 27000 CBA 321 True
    3 Audi A4 35000 ZYX 987 False
    4 NaN 29000 DEF 456 False

    我希望匹配列具有以下内容:

    Brand   Price           Liscence Plate      Match
    0 Honda Civic 22000 ABC 123 Honda
    1 Toyota Corolla 25000 XYZ 789 Toy
    2 Ford Focus 27000 CBA 321 Ford Focus
    3 Audi A4 35000 ZYX 987
    4 NaN 29000 DEF 456

    最佳答案

    你可以使用

    pattern = r'({})'.format('|'.join(sorted(search_for_these_values, key=len, reverse=True)))
    df['Match'] = df["Brand"].str.extract(pattern, expand=False)

    输出:

    >>> df
    Brand Price Liscence Plate Match
    0 Honda Civic 22000 ABC 123 Honda
    1 Toyota Corolla 25000 XYZ 789 Toy
    2 Ford Focus 27000 CBA 321 Ford Focus
    3 Audi A4 35000 ZYX 987 NaN
    4 NaN 29000 DEF 456 NaN

    详细信息:

    • sorted(search_for_these_values, key=len,verse=True) - 由于您的关键字包含多词条目,因此您需要首先确保在生成的交替模式中较长的术语出现在较短的术语之前(因为在 NFA 正则表达式中,第一个替代项匹配“获胜”,并且正则表达式库停止在当前位置搜索其余替代项)
    • '|'.join(...) - 交替模式是根据排序的关键字构建的
    • r'({})'.format(...) - 交替包含在 Series.str.extract 所必需的捕获组中正常工作(仅当正则表达式模式中至少有一个捕获组时才会输出结果)。

    关于python - 在 pandas 数据框列中搜索特定的字符串集,然后搜索该字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65818070/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com