python - 使用条件列表过滤 Pandas 中的 DataFrame

标签 python python-3.x pandas dataframe conditional-statements

我希望有一个函数接受任意长度的条件列表,并在所有条件之间放置一个符号。下面的示例代码。

df = pd.DataFrame(columns=['Sample', 'DP','GQ', 'AB'],
         data=[
               ['HG_12_34', 200, 35, 0.4],
               ['HG_12_34_2', 50, 45, 0.9],
               ['KD_89_9', 76, 67, 0.7],
               ['KD_98_9_2', 4, 78, 0.02],
               ['LG_3_45', 90, 3, 0.8],
               ['LG_3_45_2', 15, 12, 0.9]
               ])


def some_func(df, cond_list):

    # wrap ampersand between multiple conditions
    all_conds = ?

    return df[all_conds]

cond1 = df['DP'] > 40
cond2 = df['GQ'] > 40
cond3 = df['AB'] < 0.4


some_func(df, [cond1, cond2]) # should return df[cond1 & cond2]
some_func(df, [cond1, cond3, cond2]) # should return df[cond1 & cond3 & cond2]

我将不胜感激。

最佳答案

您可以为此使用 functools.reduce:

<b>from functools import reduce</b>

def some_func(df, cond_list):
    return df[<b>reduce(lambda x,y: x&y</b>, cond_list<b>)</b>]

或者,像 @AryaMcCarthy说,你可以使用 operator 包中的 and_:

from functools import reduce
<b>from operator import and_</b>

def some_func(df, cond_list):
    return df[reduce(<b>and_</b>, cond_list)]

或使用 numpy - 如 @ayhan说 - 这也有一个逻辑和减少:

<b>from numpy import logical_and</b>

def some_func(df, cond_list):
    return df[<b>logical_and.reduce(</b>cond_list<b>)</b>]

对于您的示例输入,所有三个版本都会生成以下输出:

>>> some_func(df, [cond1, cond2])
       Sample  DP  GQ   AB
1  HG_12_34_2  50  45  0.9
2     KD_89_9  76  67  0.7
>>> some_func(df, [cond1, cond2, cond3])
Empty DataFrame
Columns: [Sample, DP, GQ, AB]
Index: []

关于python - 使用条件列表过滤 Pandas 中的 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43160733/

相关文章:

python - 通过python计算文本文件中的单词

python - 使用 pandas 从 csv 中删除重复项时出现错误

Pandas 无法计算具有重复轴的 isin

python - 尝试导入请求或漂亮的汤时出现非常奇怪的错误

python - 如何在 GTK(python 3、Gio)应用程序中监听 DBus 信号?

python - 在 64 位 Windows 10 上构建/安装 PyFMI 包失败

python - pandas pivot - 总结两个字段,依赖于和独立于定义的列

java - 我无法从 java 运行 python 脚本,我认为这是因为该脚本没有执行权限

python - 确定值是否为字符串的最有效方法

python-3.x - Tensorflow-如何显示线性回归模型的准确率