如何简化或分解Python熊猫中的超长IF条件?
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)
我面临的挑战是正确地缩进
最佳答案
您可以细分为3个主要的检查功能:
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_dataframes,可以使用列表理解:
good_dataframes = [df_name for df_name, df in my_dataframes.items() if check(df)]