python - Python - 如何使用 DataFrame.query() 过滤带有 int 和 string 的列混合?
问题描述
我想根据以下一些标准过滤记录:
import pandas as pd
def doFilter(df, type, criteria):
if type=="contain":
return df[df.country.apply(str).str.contains(criteria)]
elif type=="start":
return df[df.remarks.apply(str).str.startswith(criteria)]
df= pd.read_csv("testdata.csv")
tempdf = doFilter(df, "contain", "U")
finaldf = doFilter(tempdf, "start", "123")
print(finaldf)
[测试数据.csv]
id country remarks
1 UK 123
2 UK 123abc
3 US 456
4 JP 456
[输出]
id country remarks
0 1 UK 123
1 2 UK 123abc
由于我需要通过读取不同条件的输入配置来动态过滤(例如,startswith()、contains()、endswith()、substring() 等),我想使用 DataFrame.query() 以便我可以过滤所有内容在 1 去。
例如
我尝试了许多类似于下面的方法,但没有运气:
output=df.query('country.apply(str).str.contains("U") & remarks.apply(str).str.startswith("123")')
任何帮助将不胜感激。太感谢了。
解决方案
由于您未提供样本数据,因此无法测试。
这将允许您在运行时读取过滤器并使用 pandas 内置的字符串方法应用它们。
# better to cast all relevant columns to string while setting up
df.country = df.country.astype(str)
df.remarks = df.remarks.astype(str)
# get passed filters
filter1 = [ # (field, filtertype, value, jointype)
('country', 'contains', 'U'),
('remarks', 'startswith', '123'),
]
# create a collection of boolean masks
mask = []
for field, filtertype, value in filter1:
if filtertype == 'contains':
mask.append(df[field].str.contains(value))
elif filtertype == 'startswith':
mask.append(df[field].str.startswith(value))
elif filtertype == 'endswith':
mask.append(df[field].str.startswith(value))
# all these filters need to be combined with `and`, as in `condition1 & condition2`
# if you need to allow for `or` then the whole thing gets a lot more complicated
# as you also need to expect parenthesis as in `(cond1 | cond2) & cond3`
# but it can be done with a parser
# allowing only `and` conditions
mask_combined = mask[0]
form m in mask[1:]:
mask_combined *= m
# apply filter
df_final = df[mask_combined]
推荐阅读
- swift - UIScrollView 中的 UIImageView 不会垂直居中
- ios - 如何在 ios 上从 firebase 阅读我的消息
- python - Python 2 和 Python 3 都安装在 MacOS 上,但 pip 命令安装库仅适用于 Python 3
- javascript - 用 JavaScript 识别一个没有任何属性的 HTML 元素?
- javascript - 如果 ng.for 小于表头(th),如何在表数据(td)中显示空消息?
- wordpress - 按下meniu项目后Wordpress Mobile菜单不关闭
- sql - 在sql中加入2个相互不依赖的表
- java - Jackson @JsonFormat 注释在使用导入的服务时丢失
- wpf - GUI 会话 ID 更改,我无法继续 d'automation 界面
- javascript - 如何在移动浏览器上跟踪滚动事件?