Использование:
df = df.mask(df.cumsum(axis=1).ge(1).cumsum(axis=1).isin([2,3,4]), 0)
print (df)
W1 W2 W3 W4 W5 W6 W7 W8
0 0 0 1 0 0 0 1 1
1 0 0 1 0 0 0 1 1
2 0 1 0 0 0 1 0 0
3 1 0 0 0 1 1 0 1
Объяснение :
Использование cumsum
в строках:
print (df.cumsum(axis=1))
W1 W2 W3 W4 W5 W6 W7 W8
0 0 0 1 1 2 3 4 5
1 0 0 1 1 1 2 3 4
2 0 1 1 1 2 3 3 3
3 1 1 1 1 2 3 3 4
Comapre от >=1
с ge
:
print (df.cumsum(axis=1).ge(1))
W1 W2 W3 W4 W5 W6 W7 W8
0 False False True True True True True True
1 False False True True True True True True
2 False True True True True True True True
3 True True True True True True True True
Снова cumsum
по маске Boolen:
print (df.cumsum(axis=1).ge(1).cumsum(axis=1))
W1 W2 W3 W4 W5 W6 W7 W8
0 0 0 1 2 3 4 5 6
1 0 0 1 2 3 4 5 6
2 0 1 2 3 4 5 6 7
3 1 2 3 4 5 6 7 8
Сравните на 2,3,4
для следующих 3значения с опущенным первым:
print (df.cumsum(axis=1).ge(1).cumsum(axis=1).isin([2,3,4]))
W1 W2 W3 W4 W5 W6 W7 W8
0 False False False True True True False False
1 False False False True True True False False
2 False False True True True False False False
3 False True True True False False False False
Более динамическое решение, если хотите определить n
и DIFF
значения:
df = pd.DataFrame({'W1': [0, 0, 0, 0], 'W2': [0, 0, 1, 0],
'W3': [1, 1, 0, 0], 'W4': [0, 0, 0, 0],
'W5': [1, 0, 1, 0], 'W6': [1, 1, 1, 0],
'W7': [1, 1, 0, 0], 'W8': [1, 1, 0, 1]})
print (df)
W1 W2 W3 W4 W5 W6 W7 W8
0 0 0 1 0 1 1 1 1
1 0 0 1 0 0 1 1 1
2 0 1 0 0 1 1 0 0
3 0 0 0 0 0 0 0 1
DIFF = 4
n = 3
#select columns for check by positions
subset = df.iloc[:, :n]
#replace 0 to NaNs replace back filling, change order of columns with cumsum
last_1 = subset.mask(subset == 0).bfill(axis=1).iloc[:, ::-1].cumsum(axis=1)
print (last_1)
W3 W2 W1
0 1.0 2.0 3.0
1 1.0 2.0 3.0
2 NaN 1.0 2.0
3 NaN NaN NaN
#add missing columns and create ones rows by forward filling
df1 = last_1.reindex(index=df.index, columns=df.columns).ffill(axis=1)
print (df1)
W1 W2 W3 W4 W5 W6 W7 W8
0 3.0 2.0 1.0 1.0 1.0 1.0 1.0 1.0
1 3.0 2.0 1.0 1.0 1.0 1.0 1.0 1.0
2 2.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
3 NaN NaN NaN NaN NaN NaN NaN NaN
#compare by 1 and get cumsum
print (df1.eq(1).cumsum(axis=1))
W1 W2 W3 W4 W5 W6 W7 W8
0 0 0 1 2 3 4 5 6
1 0 0 1 2 3 4 5 6
2 0 1 2 3 4 5 6 7
3 0 0 0 0 0 0 0 0
#last check range of values
df = df.mask(df1.eq(1).cumsum(axis=1).isin(range(2, DIFF + 2)), 0)
print (df)
W1 W2 W3 W4 W5 W6 W7 W8
0 0 0 1 0 0 0 0 1
1 0 0 1 0 0 0 0 1
2 0 1 0 0 0 0 0 0
3 0 0 0 0 0 0 0 1