0

Say you have 1d numpy array:

[0,0,0,0,0,1,2,3,0,0,0,0,4,5,0,0,0]

How would you create the following groups without using for loop?

[1,2,3], [4,5]

1 Answer 1

2

Here's one way using np.split:

a
# array([0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 4, 5, 0, 0, 0])
### find nonzeros
z = a!=0
### find switching points
z[1:] ^= z[:-1]
### split at switching points and discard zeros
np.split(a, *np.where(z))[1::2]
# [array([1, 2, 3]), array([4, 5])]
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to get the indexes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.