首页 > 解决方案 > 有没有办法在滚动窗口中找到倒数第二个有效索引?

问题描述

“倒数第二个有效索引”在这里只是意味着我们有一列布尔值,我们需要在最后一个布尔值为 True之前找到前一个的索引。请注意,它必须发生在滚动窗口中,而不是整个数据帧。

这与“ Is there a way to do last_valid_index() in a rolling window? ”远程相关,它回答了一个类似的问题,但找到倒数第二个而不是最后一个是完全不同的野兽。

例如:

d = {'col': [True, False, True, True, False, True, False]}

df = pd.DataFrame(data=d)

滚动窗口为 3 的“倒数第二个有效索引”方法的预期结果是:

0    NaN
1    NaN
2    0.0
3    2.0
4    2.0
5    3.0
6    3.0

(因为第 5 个索引为真:索引 3 是倒数第二个有效索引)

如果您还画了一个空白,请参阅上面的 URL 以获得类似的答案。

标签: pythonpandasdataframenumpy

解决方案


我认为你需要:

#shift Trues values and assign to new column
df['new'] = df.index.to_series()[df['col']].shift()

#get max per 3 window
df['new'] = df['new'].rolling(3, min_periods=1).max()
print (df)
     col  new
0   True  NaN
1  False  NaN
2   True  0.0
3   True  2.0
4  False  2.0
5   True  3.0
6  False  3.0

推荐阅读