如何使用 python 的迭代设置多个条件

How to set multiple conditions using an iteration for python

我正在我的数据框中寻找渐变模式,如下所示:

df.loc[(
        (df['A'].shift(-0).lt(1.7)) &
        (df['A'].shift(-1).lt(1.7)) &
        (df['A'].shift(-2).lt(1.7)) &
        (df['A'].shift(-3).lt(1.7)) &
        (df['A'].shift(-4).lt(1.7)) &
        (df['A'].shift(-5).lt(1.7)) &
]

后者将 return 一个 df,其中 6 个先前值小于 1.7 例如:

数据框将如下所示(之前和之后):

         A
329    15.1252
330    13.1251
331     1.3125
332     1.5625
333    39.5625
346    45.6875
347    11.0000
348    11.0000
354     1.8125
355     1.8125
358     1.4375
359     1.4375
360     1.5000
361     1.5000
362     1.5000
363     1.5000
364     1.4375
365     1.4375
366     1.5000 

         A
364    1.4375
365    1.4375
366    1.5000


它有效,但我想改进它。我尝试了很多东西,我认为它可能是这样的:

parameters = [
    [0, 1.7],
    [1, 1.7],
    [2, 1.7],
    [3, 1.7],
    [4, 1.7],
    [5, 1.7],
]

conditions = ([ ' & ' .join(['(df["A"].shift(-{0}).lt({1}))'.format(x[0], x[1]) for x in parameters])])
conditions = '(' + conditions ')'
df.loc[conditions]

似乎 'conditons' 被 return 编辑为引号之间的字符串,如 'conditions',所以 df.loc[条件] return 是 'KeyError'

是我在网站上的第一个问题。提前致谢。

您可以尝试在列表

上使用reduce
from functools import reduce

m = reduce((lambda df1, df2: df1&df2), [df['A'].shift(-s).lt(v) for s, v in parameters])
print(df.loc[m])

          A
358  1.4375
359  1.4375
360  1.5000
361  1.5000

一个解决方案,可能是连接所有班次,检查值小于 1.7 的地方,然后保留所有班次都通过测试的班次。

cond = pd.concat((df["A"].shift(-i) for i in range(6)), axis=1).lt(1.7).all(axis=1)

df.loc[cond]

给予

          A
358  1.4375
359  1.4375
360  1.5000
361  1.5000