首页 > 解决方案 > 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")')

任何帮助将不胜感激。太感谢了。

标签: python

解决方案


由于您未提供样本数据,因此无法测试。

这将允许您在运行时读取过滤器并使用 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]

推荐阅读