如何使用另一个条件在 pandas 中创建滚动 window

How to create a rolling window in pandas with another condition

我有一个包含 2 列的数据框

df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB'))


    A   B
0   11  10
1   61  30
2   24  54
3   47  52
4   72  42
... ... ...
95  61  2
96  67  41
97  95  30
98  29  66
99  49  22
100 rows × 2 columns

现在我想创建第三列,它是滚动的 window max of col 'A' 但是 最大值必须低于 col 'B' 中的相应值。换句话说,我希望 'A' 列中 4 的值(使用 window 大小为 4)最接近 col 'B' 中的值,但小于 B

例如在行中 3 47 52 我正在寻找的新值不是 61 而是 47,因为它是 4 中不高于 52

的最高值

伪代码

df['C'] = df['A'].rolling(window=4).max()  where < df['B']

您可以使用concat + shift 来创建一个包含以前值的宽DataFrame,这使得复杂的滚动计算更容易一些。

示例数据

np.random.seed(42)
df = pd.DataFrame(np.random.randint(0, 100, size=(100, 2)), columns=list('AB'))

代码

N = 4
# End slice ensures same default min_periods behavior to `.rolling`
df1 = pd.concat([df['A'].shift(i).rename(i) for i in range(N)], axis=1).iloc[N-1:]

# Remove values larger than B, then find the max of remaining.
df['C'] = df1.where(df1.lt(df.B, axis=0)).max(1)

print(df.head(15))

     A   B     C
0   51  92   NaN  # Missing b/c min_periods
1   14  71   NaN  # Missing b/c min_periods
2   60  20   NaN  # Missing b/c min_periods
3   82  86  82.0
4   74  74  60.0
5   87  99  87.0
6   23   2   NaN  # Missing b/c 82, 74, 87, 23 all > 2
7   21  52  23.0  # Max of 21, 23, 87, 74 which is < 52
8    1  87  23.0
9   29  37  29.0
10   1  63  29.0
11  59  20   1.0
12  32  75  59.0
13  57  21   1.0
14  88  48  32.0

您可以使用自定义函数.apply来滚动window。在这种情况下,您可以使用默认参数传入 B 列。

df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=('AB'))

def rollup(a, B=df.B):
    ix = a.index.max()
    b = B[ix]
    return a[a<b].max()

df['C'] = df.A.rolling(4).apply(rollup)

df
# returns:
     A   B     C
0    8  17   NaN
1   23  84   NaN
2   75  84   NaN
3   86  24  23.0
4   52  83  75.0
..  ..  ..   ...
95  38  22   NaN
96  53  48  38.0
97  45   4   NaN
98   3  92  53.0
99  91  86  53.0

当 A 的 window 中没有数字小于 B 时,或者当 window 对于前几个数字太大时,在系列开始时出现 NaN 值行。

您可以使用where将不满足条件的值替换为np.nan,然后使用rolling(window=4, min_periods=1):

In [37]: df['C'] = df['A'].where(df['A'] < df['B'], np.nan).rolling(window=4, min_periods=1).max()                                                                                            

In [38]: df                                                                                                                                                                                   
Out[38]: 
    A   B    C
0   0   1  0.0
1   1   2  1.0
2   2   3  2.0
3  10   4  2.0
4   4   5  4.0
5   5   6  5.0
6  10   7  5.0
7  10   8  5.0
8  10   9  5.0
9  10  10  NaN