3

If I have a numpy array say

A = [[1,2],[3,4],[5,6],[7,8]]

and a list

L = [1,0,1,1]

Is there a way to split A down axis0 based off of if they are a 1/0 in L? This would be my desired result:

A1 = [[1,2],[5,6],[7,8]]
A2 = [[3,4]]

1 Answer 1

6

Since L is binary, you can convert L to boolean type and then use boolean indexing:

A = np.array([[1,2],[3,4],[5,6],[7,8]])
L = np.array([1,0,1,1])

L = L.astype(bool)
A1, A2 = A[L], A[~L]

A1
#array([[1, 2],
#       [5, 6],
#       [7, 8]])

A2
#array([[3, 4]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer! I never knew about binary indexing, so this was very helpful.

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.