python - 动态搜索: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]))
]
解决方案
怎么样
submasks = [df['Column'].str.contains(s) for s in words]
combined = np.vstack(submasks).all(axis=0)
df[combined]
推荐阅读
- typescript - 阻止 WebStorm 建议索引导入
- docker - Hashicorp Vault-创建数据库对象时出错-MongoDB
- flutter - Flutter Qs:未处理的异常:“String”类型不是“FutureOr”类型的子类型
- javascript - 如何在 OTP 无效之前将其存储特定时间
- python - 无法从python中双列表中存在的字典中提取键值
- c# - 当 T 定义为数组时,如何将对象数组转换/转换为泛型类型 T?
- php - Laravel 8 GroupBy 仅向我返回每个组的第一条记录,但我需要按组中的所有记录
- sql - 如何在 Business Intelligence Publisher (BIP) 中使用过程调用和非标准 SQL
- amazon-web-services - Amazon ECS 容量提供程序未在 target_capacity=100 处横向扩展实例
- vue.js - 在 vuex 状态改变后做点什么