如何简化或分解Python pandas中的超长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)对我来说最大的挑战就是把正确的缩进
发布于 2020-01-04 08:36:50
您可以在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)]发布于 2020-01-04 08:08:03
定义包含条件的函数。
def is_good_df(df):
return (((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()))一个好的IDE应该有助于获得正确的缩进。
请注意,在某些.all调用之后,您还缺少()。
然后你就可以
my_dataframes = {'d1': d1, 'd2': d2,'d3': d3}
good_dataframes = [df_name for df, df_name in my_dataframes.items() if is_good_df(df)]发布于 2020-01-04 08:08:34
这是否会让它变得更容易理解:
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)https://stackoverflow.com/questions/59586706
复制相似问题