【问题标题】:pythonic way to apply multiple filters to a dataframe based on user input基于用户输入将多个过滤器应用于数据帧的pythonic方法
【发布时间】:2020-11-01 08:26:26
【问题描述】:

假设我有一个名人数据框,包括他们的年龄、种族、身高、行业等。

我想创建一个函数,我可以在其中系统地过滤数据框,以便可以应用多个过滤器。

例如

def filter_data(df, filter_col, filter_val, filter_amount):
    if filter_amount == 1:
        df = df[df.filter_col[0] == filter_val[0]]
    if filter_amount == 2:
        df = df[(df.filter_col[0] == filter_val[0]) & (df.filter_col[1] == filter_val[1])]

    etc

其中 filter_col 是您希望作为过滤依据的列的列表,filter_val 也是一个值列表,而 filter_amount 是一个整数

我希望它是系统性的,以便对于任何过滤器数量,它都可以根据列表的值继续过滤数据集,而无需手动对其进行编码

帮助。

【问题讨论】:

标签: python pandas numpy dataframe pandas-groupby


【解决方案1】:
filter_vals = [1, 2, 3]
filter_amount = 3

filtered_df = [df[df[col] == val] for val in filter_vals] 

【讨论】:

  • 不应该是这样的:filtered_df = [df[df[col] == val] for val in filter_vals]?当前代码将产生语法错误
  • 是的,我忘了括号,现在添加它们
【解决方案2】:

由于过滤器执行 and (&),所以这样做是有意义的:

import pandas as pd

def filter_data(df, filter_col, filter_val, filter_amount):
    out = df.copy()
    for i in range(filter_amount):
        out = out[out[filter_col[i]] == filter_val[i]]
    return out

def main():
    x = pd.DataFrame({"Age": [12, 44, 23], "Ethnicity": ["White", "Black", "White"], "Height": [180, 182, 168]})
    #    Age Ethnicity  Height
    # 0   12     White     180
    # 1   44     Black     182
    # 2   23     White     168

    y = filter_data(x, ["Ethnicity", "Height"], ["White", 180], 1)
    #    Age Ethnicity  Height
    # 0   12     White     180
    # 2   23     White     168

    z = filter_data(x, ["Ethnicity", "Height"], ["White", 180], 2)
    #    Age Ethnicity  Height
    # 0   12     White     180

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2018-06-07
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多