首页 > 解决方案 > 动态搜索:Pandas 数据框查询

问题描述

我正在尝试使用字符串(单词或短语)用户输入来搜索特定列中的子字符串以查询结果。我怎样才能使它动态?即我想继续添加单词作为新查询来定位项目而不必定义它。

例如。如果输入是 - 'word1'; 它返回 df['column'] 中所有带有 'word1' 的行

如果输入是 - 'word1 word2 wordn'; 它使用如下查询返回所有行:

x = input("Type to search for item : ")  # input phrase or word
words = x.split(' ')

query = df.loc[(df['Column'].str.contains(words[0]))
           &(df['Column'].str.contains(words[1]))
           &(df['Column'].str.contains(words[n]))
           ]

标签: pythonpandasstring

解决方案


怎么样

submasks = [df['Column'].str.contains(s) for s in words]
combined = np.vstack(submasks).all(axis=0)
df[combined]

推荐阅读