gpt4 book ai didi

python - 在不预定义要使用的字符串数的情况下在 Pandas 中搜索多个字符串

转载 作者:太空狗 更新时间:2023-10-29 17:39:01 26 4
gpt4 key购买 nike

我想知道是否有更通用的方法来执行以下操作?我想知道是否有办法创建 st 函数以便我可以搜索非预定义数量的字符串?

例如,能够创建一个通用的 st 函数,然后键入 st('Governor', 'Virginia', 'Google)

这是我当前的函数,但它预定义了两个您可以使用的词。 (df 是一个 Pandas 数据框)

def search(word1, word2, word3 df):
"""
allows you to search an intersection of three terms
"""
return df[df.Name.str.contains(word1) & df.Name.str.contains(word2) & df.Name.str.contains(word3)]

st('Governor', 'Virginia', newauthdf)

最佳答案

你可以使用np.logical_and.reduce:

import pandas as pd
import numpy as np
def search(df, *words): #1
"""
Return a sub-DataFrame of those rows whose Name column match all the words.
"""
return df[np.logical_and.reduce([df['Name'].str.contains(word) for word in words])] # 2


df = pd.DataFrame({'Name':['Virginia Google Governor',
'Governor Virginia',
'Governor Virginia Google']})
print(search(df, 'Governor', 'Virginia', 'Google'))

打印

                       Name
0 Virginia Google Governor
2 Governor Virginia Google

  1. def search(df, *words) 中的* 允许search 接受一个无限数量的位置参数。它将收集所有参数(在第一个之后)并将它们放在名为 words 的列表中。
  2. np.logical_and.reduce([X,Y,Z])等同于 X & Y & Z。它但是,允许您处理任意长的列表。

关于python - 在不预定义要使用的字符串数的情况下在 Pandas 中搜索多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22623977/

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