python - Pandas - 创建多个过滤器并应用于数据框

标签 python pandas

我为数据框创建了多个过滤器:

filt1 = ~df["message"].str.contains("<Media omitted>", na=False),
filt2 = ~df["message"].str.contains("http://", na=False),
filt3 = ~df["message"].str.contains("Dropped pin", na=False), 

我可以使用以下方法过滤数据框:

df[filt1 & filt2 & filt3]

但是当我添加更多过滤器时,这似乎是一种愚蠢的过滤方式。 如何将多个过滤器应用于数据框?

我尝试将每个过滤器添加到列表中,执行 df[filterlist]df[*filterlist] 但这些不起作用。

最佳答案

您可以使用np.logical_and.reduce :

filterlist = [filt1, filt2, filt3]

df[np.logical_and.reduce(filterlist)]

或者concatDataFrame.all用于测试每行的所有 True:

df[pd.concat(filterlist, axis=1).all(axis=1)]

如果可能,请使用|作为正则表达式:

filt = ~df["message"].str.contains("<Media omitted>|http://|Dropped pin", na=False)

关于python - Pandas - 创建多个过滤器并应用于数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63560043/

相关文章:

python - 尝试使用 python 计算斐波那契数的最后一位时出现错误 "RuntimeWarning: overflow encountered in long_scalars"

python - Plotly 中的行悬停文本

python - 如何从每个一级指标中最大的二级指标的单元格中取值?

python - Pandas :如何找到一个群体的百分比?

python - Pandas 错误 : "IndexError: iloc cannot enlarge its target object"

python - 在执行中断后检索 keras 模型拟合历史

python - 使用 python 在 Windows 10 上检测 USB 设备插入

Python GroupBy 时间间隔

python Pandas : Add column based on other column

python - 如何在 Python 中将表示为字符的数字简称为数字