遍历列表以构建OR语句 [英] Iterating through a list to build an OR statement

查看:75
本文介绍了遍历列表以构建OR语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数接受一个DataFrame并对由OR连接的特定列执行一系列过滤器.我只需要一列低于96的列即可通过过滤器.

I have a function that takes a DataFrame and performs a series of filters on specific columns that are joined by OR . I only need one column to be below 96 to pass the filter.

此代码可以正常工作,但我想改进该功能,以便能够将list传递给该函数,该函数将成为过滤器,而不是将列硬编码到该函数中.

This code works fine but I'd like to improve the function to be able to pass the function a list that would be the filter rather then have the columns hardcoded into the function.


def remove_never_used_focus(drugs, df):
    """ Filters out values above 95 which are
    codes for never used or not answered """

    df = df[
        (df['CAN_060'] < 96) |
#         (df['ALC_30'] < 96) |
        (df['PS_30'] < 96) |
        (df['COC_20'] < 96) |
        (df['HAL_20'] < 96) |
        (df['MET_20'] < 96) |
        (df['XTC_20'] < 96) |
        (df['GLU_20'] < 96) |
        (df['HER_20'] < 96) |
        (df['SAL_20'] < 96) 
        ]

    # this produces and `AND` statement I would like and `OR` statement
    for drug in drugs:
        df = df[(df[drug]) < 96]

    display(df)

    return df

我想到构建此语句的唯一方法是遍历list并逐步构建它.但是,这会生成一个AND语句.

The only way I can think of to build this statement is by iterating through the list and progressively building it. However, this produces an AND statement.

推荐答案

使用


df1 = df[(df[cols] < 96).any(axis=1)]
print (df1)
   A  CAN_060  PS_30  COC_20  E  F
1  b      512      8       3  3  a
2  c        4      9       5  6  a
3  d        5      4       7  9  b
4  e        5    200     100  2  b

#for AND for testing if all values per rows are True
df2 = df[(df[cols] < 96).all(axis=1)]
print (df2)
   A  CAN_060  PS_30  COC_20  E  F
2  c        4      9       5  6  a
3  d        5      4       7  9  b

这篇关于遍历列表以构建OR语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆