I'm new to this, so this is probably a basic question, but how do I remove values from my array that are less than 0?
So, if
a=np.random.randint(-10,11,(10,10))
How would I create an array with only the positive values from a? thanks
I'm new to this, so this is probably a basic question, but how do I remove values from my array that are less than 0?
So, if
a=np.random.randint(-10,11,(10,10))
How would I create an array with only the positive values from a? thanks
The native python way to do it would be a comprehension list :
filtered = [x for x in a if x>0]
For numpy ways of doing it have a look at this similar question : Filtering a NumPy Array: what is the best approach?
In Numpy you can use what is known as fancy indexing for this kind of tasks.
In [26]: a = np.random.randint(-10,11,(10,10))
In [27]: a
Out[27]:
array([[ -6, 2, 8, -8, -7, 7, 5, 0, 10, 5],
[ -3, -7, 5, 0, 3, 7, 3, 10, -9, 0],
[ 1, 8, -8, -2, 4, 2, -7, 10, -3, -5],
[ 7, 1, 3, -2, 1, 8, 7, 6, -4, 0],
[ -5, 6, -2, -7, -10, -9, 9, 9, -5, 8],
[ 4, 3, -7, 1, 4, 1, -6, 7, -6, -5],
[ -5, -5, 4, -7, -6, -6, 10, -2, -8, 8],
[ -9, 4, 2, 10, -7, -5, 3, 5, 9, 1],
[ -9, -7, -3, -8, -4, -7, -6, -5, 1, -9],
[ -7, -4, -8, 5, -10, 1, 2, -8, -2, 10]])
In [28]: a[a!=0] #this is the fancy indexing (non 0 elements)
Out[28]:
array([ -6, 2, 8, -8, -7, 7, 5, 10, 5, -3, -7, 5, 3,
7, 3, 10, -9, 1, 8, -8, -2, 4, 2, -7, 10, -3,
-5, 7, 1, 3, -2, 1, 8, 7, 6, -4, -5, 6, -2,
-7, -10, -9, 9, 9, -5, 8, 4, 3, -7, 1, 4, 1,
-6, 7, -6, -5, -5, -5, 4, -7, -6, -6, 10, -2, -8,
8, -9, 4, 2, 10, -7, -5, 3, 5, 9, 1, -9, -7,
-3, -8, -4, -7, -6, -5, 1, -9, -7, -4, -8, 5, -10,
1, 2, -8, -2, 10])
In [29]: a[a>0] #fancy indexing again (all positive elements)
Out[29]:
array([ 2, 8, 7, 5, 10, 5, 5, 3, 7, 3, 10, 1, 8, 4, 2, 10, 7,
1, 3, 1, 8, 7, 6, 6, 9, 9, 8, 4, 3, 1, 4, 1, 7, 4,
10, 8, 4, 2, 10, 3, 5, 9, 1, 1, 5, 1, 2, 10])