what_the_bird
what_the_bird

Reputation: 3

Extract the first and last indices of all sequences of 1s in a numpy array and append them to a list?

I have a mask vector for an audio file (time series) that contains 1s and 0s. The mask vector will contain long sequences of 1s for the intervals in the audio signal when there is some favourable activity and 0s when there is noise. I want to basically extract all the activity parts from the audio signal and store them as separate audio files. For this reason, it would be helpful if I could find the most efficient way of extracting the start and end indices of all sequences of 1s from the mask vector and append them for instance to a list.

Upvotes: 0

Views: 171

Answers (1)

user17242583
user17242583

Reputation:

I'd do something like this:

groups = df.groupby(df['your_col'].ne(df['your_col'].shift(1)).cumsum()[df['your_col'].eq(1)])
for _, group in groups:
    # At this point, 'group' is a separate dataframe containing all the rows where 'your_col' is consecutively 1
    # ...

Basically what that does is it groups the rows by consecutive 1s (each group of one or more zeros ends the previous group of 1s), and then loops over each group (which is a portion of the original dataframe).

Upvotes: 1

Related Questions