如何在其他条件下在 pandas 中创建滚动窗口

2024-02-18

我有一个包含 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

现在我想创建第三列,它是 col 'A' 的滚动窗口最大值,但是 最大值必须低于“B”列中的相应值。换句话说,我希望列“A”中的 4 的值(使用窗口大小为 4)最接近列“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'))

Code

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在其他条件下在 pandas 中创建滚动窗口 的相关文章

随机推荐