如何在熊猫数据帧中将大小超过指定阈值的批量一起出现的 1 (ON) 标志切换为 0?



pandas 数据帧中的标志列由10填充

问题是识别连续1

t天数阈值 需要两种类型的转换: i( 如果一起有超过 t 个 1,请将(t+1)th向上 1 转到 0 ii( 如果一起有超过 t 个 1,请将所有 1 变为 0

我的方法是创建 2 列,称为result1result2,并使用这些列进行过滤:

请看图片

这里我一直无法想到这样的事情,所以不发布任何代码。在正确方向上的推动或提示将不胜感激。

使用:

#compare 0 values
m = df['Value'].eq(0)
#get cumulative sum and filter only 1 rows
g = m.cumsum()[~m]
#set by condition - 0 or ccounter per groups
df['Result1'] = np.where(m, 0, df.groupby(g).cumcount().add(1))
#get maximum per groups with transform for new Series
df['Result2'] = np.where(m, 0, df.groupby(g)['Result1'].transform('max')).astype(int)

print (df)
Value  Result1  Result2
0       1        1        1
1       0        0        0
2       0        0        0
3       1        1        2
4       1        2        2
5       0        0        0
6       1        1        4
7       1        2        4
8       1        3        4
9       1        4        4
10      0        0        0
11      0        0        0
12      1        1        1
13      0        0        0
14      1        1        1
15      0        0        0
16      0        0        0
17      1        1        6
18      1        2        6
19      1        3        6
20      1        4        6
21      1        5        6
22      1        6        6
23      0        0        0
24      1        1        1
25      0        0        0
26      0        0        0
27      1        1        1
28      0        0        0

最新更新