2

say you have following array

a = np.array([[-1,-2,-3,4],[6,-1,-3,-4],[3,2,5,6]])

and you want all rows, where position 0, 1 and 2 are < 0.

So far i found follwing unelegant solutions:

b = a[np.logical_and(a[:, 0]<0, a[:, 1]<0, a[:, 2]<0)]

or

c= a[np.where((a[:, 0]<0) * (a[:, 1]<0) * (a[:, 2]<0))]

considering that i want to deal with huge arrays, that would be a pretty bad way to solve it.

Any ideas?

1 Answer 1

4

You can simply use:

b = a[np.all(a[:,:3] < 0,axis=1)]

So you can first construct a submatrix by using slicing a[:,:3] will construct a matrix for the first three columns of the matrix a. Next we use < 0 to check if all these elements are less than zero.

We then will perform a logical and on every row (by anding the columns together). This will construct a 1D matrix for every row. An element will be True if all the three columns are True. Otherwise it is False.

Finally we use masking to construct a submatrix where the first three columns are all less than 0. This will probably work faster since the number of numpy calls is less and thus we do more work per call.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you are my hero

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.