python - 过滤多列 Pandas

标签 python pandas

我有一个将 pandas 数据框作为输入的方法:

def dfColumnFilter(df, columnFilter, columnName):
    ''' Returns a filtered DataFrame

    Keyword arguments: 
    df           :  DataFrame in which to apply the filter
    columnFilter :  The list of which to filter by
    columnName   :  The DataFrame column to apply the columnFilter to '''

    for column_filter in columnFilter:
        df=df[df[columnName] == column_filter]
        return df

问题是我如何让 n 列工作?

最佳答案

您可以使用 *args传递成对列表的关键字:

def filter_df(df, *args):
    for k, v in args:
        df = df[df[k] == v]
    return df

可以这样使用:

df = pd.DataFrame({'a': [1, 2, 1, 1], 'b': [1, 3, 3, 3]})

>>> filter_df(df, ('a', 1), ('b', 2))
    a   b
2   1   3
3   1   3

注意

理论上,你可以使用**kwargs,这会有更令人愉快的用法:

filter_df(df, a=1, b=2)

但是您只能将它用于名称为有效 Python 标识符的列。

编辑

请参阅下面@Goyo 的评论以获得更好的实现点。

关于python - 过滤多列 Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35131096/

相关文章:

python-3.x - 使用条件回填 Pandas 数据框列

python - 修改具有日期偏移量的数据框

python - 将 Voigt 函数拟合到 Python 中的数据

python - Pandas 与列上的条件合并

python - 应用于 pandas 数据框中的两列时出现 Difflib 错误

python - OpenCV(Python)中cv2.findHomography的输出

python - Pandas 将不规则的时间序列与不同的频率对齐

Python 线程化子函数

python - C++ 和 Python 之间/中的区别

python - Pandas :在文本列中搜索关键字列表并对其进行标记