There must a be a (very) quick and efficient way to get only elements from a numpy array, or even more interestingly from a slice of it. Suppose I have a numpy array:
import numpy as np a = np.arange(-10,10)
Now if I have a list:
s = [9, 12, 13, 14]
I can select elements from a:
a[s] #array([-1, 2, 3, 4])
How can I have an (numpy) array made of the elements from a[s] that fulfill a condition, i.e. are positive (or negative)? It should result
np.ifcondition(a[s]>0, a[s]) #array([2, 3, 4])
It looks trivial but I was not able to find a simple and condensed expression. I'm sure masks do but it's doesn't look really direct to me. However, neither:
a[a[s]>0] a[s[a[s]>0]]
are in fact good choices.
To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.
You select a value from an array by referring to the index of its element. Array elements (the things inside your array), are numbered/indexed from 0 to length-1 of your array.
How about:
In [19]: b = a[s] In [20]: b[b > 0] Out[20]: array([2, 3, 4])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With