Python分解了超长的IF语句 [英] Python break down a super long IF statement

查看:142
本文介绍了Python分解了超长的IF语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何简化或分解Python大熊猫中的超长IF条件?

How to simplify or break down the super long IF Condition in Python pandas?

my_dataframes = {'d1': d1, 'd2': d2,'d3': d3}
good_dataframes = []
for df_name, df in my_dataframes.items():
    if ((df.loc[1:4, 'test'] <= 6).all() 
        and (df.loc[5:9, 'dif'] < 9).all()) or ((df.loc[1:5, 'test'] <= 6).all() 
                                                      and (df.loc[5:8, 'dif'] < 8).all()) or ((df.loc[1:8, 'test'] <= 6).all() 
                                                                                                    and (df.loc[5:8, 'dif'] < 9).all()):
        good_dataframes.append(df_name)

对我来说挑战是正确的缩进

the challenge for me is put the right indent

推荐答案

您可以细分为3个主要的检查功能:

you can break down in 3 major check functions:

my_dataframes = {'d1': d1, 'd2': d2,'d3': d3}

def check_1(df):
    return (df.loc[1:4, 'test'] <= 6).all() and (df.loc[5:9, 'dif'] < 9).all()

def check_2(df):
    return (df.loc[1:5, 'test'] <= 6).all() and (df.loc[5:8, 'dif'] < 8).all()

def check_3(df):
    return (df.loc[1:8, 'test'] <= 6).all() and (df.loc[5:8, 'dif'] < 9).all()

CHECK_FUNCTIONS = (check_1, check_2, check_3)

def check(df):
    return any(check_f(df) for check_f in CHECK_FUNCTIONS)

good_dataframes = []
for df_name, df in my_dataframes.items():

    if  check(df):
        good_dataframes.append(df_name)

要获取good_dataframe,可以使用列表理解:

to obtain good_dataframes you can use a list comprehension:

good_dataframes = [df_name for df_name, df in my_dataframes.items() if check(df)]

这篇关于Python分解了超长的IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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