-2

I have a pandas series:

s = [3,7,8,0,0,0,6,12,0,0,0,0,0,8,5,0,2]

I want to find all the indices in which there is a start or an end of a zeros segment, where the number of zeros is more than 3 so here I want to get:

[8,12]

What is the best way to do so?

Thanks

Cranjis
  • 1,590
  • 8
  • 31
  • 64

3 Answers3

1

I found this way using more_itertools considering s is the series (not list as you have provided):

First group the list in consecutive elements for the index that meets the condition:

import more_itertools as mit
a = [list(group) for group in mit.consecutive_groups(s.loc[s.eq(0)].index.tolist())]

Second , select the first and last entries form the list

list(set([i[0] for i in a]+[x[-1] for x in a]))
#[3, 5, 8, 12, 15]

EDIT for getting first and last index where 0 is more than 3 use:

list(set([i[0] for i in a if len(i)>3]+[x[-1] for x in a if len(x)>3]))
#[8, 12]
anky
  • 74,114
  • 11
  • 41
  • 70
  • thank you , and if I want the segment of zeros will be with more than 3 zeros? – Cranjis Feb 15 '19 at 11:29
  • @okuoub didnt get that. you wanted the first and last index of consecutive zeroes right? the code does the same? – anky Feb 15 '19 at 11:31
  • yes but I want to filter out segments with less than 3 zeros (please see the edit) – Cranjis Feb 15 '19 at 11:35
  • @okuoub check EDIT acc to the new question use same solution with `list(set([i[0] for i in a if len(i)>3]+[x[-1] for x in a if len(x)>3]))` – anky Feb 15 '19 at 11:37
1
s = [3,7,8,0,0,0,6,12,0,0,0,0,0,8,5,0,2]
idx = []
for i in range(len(s)):
    if s[i] == 0 and (s[i+1] != 0 or s[i-1] != 0):
        idx.append(i)
print (idx)
# result :[3, 5, 8, 12, 15]
ncica
  • 7,015
  • 1
  • 15
  • 37
0

Define a flag that tells the loop whether to check the existence or absence of 0. entryFlag tells whether to check the entry of 0s or the exit.

s = [3,7,8,0,0,0,6,12,0,0,0,0,0,8,5,0,2]
entryFlag=True
i=0
s2=[]
for x in s:

    if entryFlag:
        if x==0:
            s2.append(i)
            entryFlag=False
    else:
        if x!=0:
            s2.append(i-1)
            entryFlag=True
    i+=1
print(s2)
Abhinay Pandey
  • 46
  • 3
  • 15