gpt4 book ai didi

Python分解超长IF语句

转载 作者:行者123 更新时间:2023-12-02 10:59:26 26 4
gpt4 key购买 nike

如何简化或分解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)

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

最佳答案

定义一个包含条件的函数。

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)]

关于Python分解超长IF语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com