0

I'm currently writing a code, and I have to extract from a numpy array.

For example: [[1,1] , [0.6,0.6], [0,0]]), given the condition for the extracted points [x,y] must satisfy x>=0.5 and y >= 0.5

I've tried to use numpy extract, with the condition arr[0]>=0.5 & arr[1]>=0.5 however that does not seem to work

It applied the condition on all the elements, and I just want it to apply to the points inside my array.

Thanks in advance!

3
  • Can you share the code you used? Commented Jul 24, 2019 at 17:40
  • [[x,y] for x,y in a if x>=0.5 and y>=0.5] Commented Jul 24, 2019 at 17:43
  • 1
    Your condition doesn't work because of the way it is being parsed. Wrap each side of the expression in parenthesis or you will get a TypeError Commented Jul 24, 2019 at 17:43

3 Answers 3

2

You can use multiple conditions to slice an array as follows:

import numpy as np

a = np.array([[1, 1] , [0.6, 0.6], [0, 0]])
new = a[(a[:, 0] >= 0.5) & (a[:, 1] >= 0.5)]

Results:

array([[1. , 1. ],
       [0.6, 0.6]])

The first condition filters on column 0 and the second condition filters on column 1. Only rows where both conditions are met will be in the results.

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

2 Comments

I have one more question: if for example my bounds are stored in a numpy array (for example i want to extract elements which are pairwise greater than 0.5, then do the same thing with 1, then with 1.5 i.e i store [0.5,1, 1.5] in an array), how would i do it in a nice vectorized way instead of looping over the list?
@cyborg42 - I'm sure it can be done, but we'd need to know exactly what output format you're looking for. I would recommend asking it as a new question with clear example input and desired output.
0

I would do it following way: firstly look for rows full-filling condition:

import numpy as np
a = np.array([[1,1] , [0.6,0.6], [0,0]])
rows = np.apply_along_axis(lambda x:x[0]>=0.5 and x[1]>=0.5,1,a)

then use it for indexing:

out = a[rows]
print(out)

output:

[[1.  1. ]
 [0.6 0.6]]

Comments

0

It can be solved using python generators.

import numpy as np

p = [[1,1] , [0.6,0.6], [0,0]]
result = np.array([x for x in p if x[0]>0.5 and x[1]>0.5 ])

You can read more about generators from here.

Also you can try this:-

p = np.array(p)
result= p[np.all(p>0.5, axis=1)]

Comments

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.