我想知道是否有更通用的方法来做下面的事情?我想知道是否有办法创建st函数,以便我可以搜索非预定义数量的字符串?
例如,能够创建一个通用的st函数,然后输入st(‘Governor’,’Virginia’,’Google)
这是我当前的功能,但它预定义了两个可以使用的单词. (df是一个pandas DataFrame)
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
> def搜索中的*(df,* words)允许搜索接受
无限数量的位置参数.它会收集所有的
参数(在第一个之后)并将它们放在一个名为words的列表中.
> np.logical_and.reduce([X,Y,Z])相当于X& Y& Z.它
但是,允许您处理任意长的列表.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。