Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a numpy array using a binary list?

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]]
like image 859
Ammastaro Avatar asked Jul 28 '26 06:07

Ammastaro


1 Answers

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]])
like image 53
Psidom Avatar answered Jul 29 '26 19:07

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!