我有一个包含 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
现在我想创建第三列,这是一个滚动窗口 max of col 'A' BUT 最大值必须低于列“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'))
代码
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
关于python - 如何在另一种情况下在 Pandas 中创建滚动窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60765866/