0

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

例如。如果输入是 - '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]))
           ]
4

2 回答 2

0

怎么样

submasks = [df['Column'].str.contains(s) for s in words]
combined = np.vstack(submasks).all(axis=0)
df[combined]
于 2020-05-28T15:21:42.200 回答
0

考虑Series.str.contains使用带有AND逻辑的正则表达式:

words_pattern = r"(" + ")(".join(words) + ")"

sub_df = df.loc[df['char'].str.contains(words_pattern, regex=True)]

或者,根据使用正则表达式字符串分组的警告,使用Series.str.extract

words_pattern = r"(" + ")(".join(words) + ")"

res = df['char'].str.extract(words_pattern)
sub_df = df.loc[res.dropna().index]
于 2020-05-28T15:32:20.507 回答