당신은 할 수 :
df['consecutive'] = df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count
이 얻을 : 당신이 할 수있는 여기에서
Count consecutive
0 1 1
1 0 0
2 1 2
3 1 2
4 0 0
5 0 0
6 1 3
7 1 3
8 1 3
9 0 0
을 어떤 임계 값 :
threshold = 2
df['consecutive'] = (df.consecutive > threshold).astype(int)
0 하나의 단계에서,
Count consecutive
0 1 0
1 0 0
2 1 1
3 1 1
4 0 0
5 0 0
6 1 1
7 1 1
8 1 1
9 0 0
또는 :
취득하는 pandas
방법을 사용하여
효율성의 측면에서
(df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count >= threshold).astype(int)
가 제공 상당한 속도 향상을 문제의 크기가 커지면 :
df = pd.concat([df for _ in range(1000)])
%timeit (df.Count.groupby((df.Count != df.Count.shift()).cumsum()).transform('size') * df.Count >= threshold).astype(int)
1000 loops, best of 3: 1.47 ms per loop
과 비교했을 때
%%timeit
l = []
for k, g in groupby(df.Count):
size = sum(1 for _ in g)
if k == 1 and size >= 2:
l = l + [1]*size
else:
l = l + [0]*size
pd.Series(l)
10 loops, best of 3: 76.7 ms per loop
'df [ 'Count'] [1] == df [ 'Count'] [1] .shift (1)', 그리고 '1'이면'0'을 확인하십시오. 그런 다음이 값 (0 또는 1)을'array'에'.append()'해야합니다. 그런 다음 첫 번째 요소 ('array [0]')를'0' (기본값)으로 설정하십시오. 그렇다면'array '를'dataframe'에'merge/join/plug/concatenate'하는 법을 알아야합니다. 100 % 테스트되지 않은,하지만이 작동하지 않을 수 있습니다 생각 ... :) –
내가 너무 많이 내 질문을 단순화했을 수도 있습니다, 만약 내가 3 연속 사건을 원한다면? 나는 이것이 작동하지 않는다고 생각한다. –