【发布时间】:2020-02-17 09:50:22
【问题描述】:
我有以下数据框:
A B C
0 1 1 1
1 0 1 0
2 1 1 1
3 1 0 1
4 1 1 0
5 1 1 0
6 0 1 1
7 0 1 0
当每列 3 个或更多连续值的值为 1 时,我想知道开始和结束索引。期望的结果:
Column From To
A 2 5
B 1 3
B 4 7
首先我过滤掉不连续的3个或更多值
filtered_df = df.copy().apply(filter, threshold=3)
在哪里
def filter(col, threshold=3):
mask = col.groupby((col != col.shift()).cumsum()).transform('count').lt(threshold)
mask &= col.eq(1)
col.update(col.loc[mask].replace(1,0))
return col
filtered_df 现在看起来像:
A B C
0 0 1 0
1 0 1 0
2 1 1 0
3 1 0 0
4 1 1 0
5 1 1 0
6 0 1 0
7 0 1 0
如果数据框只有一列带有 0 和 1,则可以像 How to use pandas to find consecutive same data in time series 那样实现结果。但是,我正在努力一次对多个列执行类似的操作。
【问题讨论】:
-
也许将您的代码打包在一个函数中,然后将该函数作为一个整体应用于数据帧?您当然需要扩展
filter函数以将其应用于 df.columns 中的每个列。