python - 有没有办法在滚动窗口中找到倒数第二个有效索引?
问题描述
“倒数第二个有效索引”在这里只是意味着我们有一列布尔值,我们需要在最后一个布尔值为 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 以获得类似的答案。
解决方案
我认为你需要:
#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
推荐阅读
- javascript - 将大小数四舍五入到最接近的小数
- django - 这是从 django 中的 chechboxes 保存多个数据的最佳方法
- mysql - 请帮助使用两个表和 M:N 行映射优化 MySql UPDATE
- ubuntu - 我可以使用 podman 无根运行 bash 吗?
- python - 匹配不同文件中的字符串并连接值
- typescript - 打字稿文件为空导致问题
- javascript - 在 iOS 版 Google Chrome 上的数据 URL 上,锚标记的下载属性被忽略
- dynamics-365 - 动态映射
- java - 递归计算二叉树中的叶子数
- laravel - Laravel Sanctum auth:sanctum 路由允许在没有承载令牌的情况下访问