Reputation: 479
I haven't use numpy to his full potential yet. I have this pretty huge 3d array (700000 x 32 x 32). All of the values are int between 1 and 4. I want to be able to filter the array so that the I get a same shape array, but only with 1 for values of 4 and 0 for everything else.
For example,
[[4, 2, 2, 3], [[1, 0, 0, 0],
[1, 4, 4, 2], [0, 1, 1, 0],
[2, 4, 1, 3], -> [0, 1, 0, 0],
[2, 3, 2, 4]] [0, 0, 0, 1]]
It works with np.where(array==4)
. I get a huge 3d array that I can reshape, but would there more numpy way to do it ? Thanks.
Upvotes: 1
Views: 328
Reputation: 529
You can also get it with np.where without having to reshape it with the next expression:
arr = np.array([[4, 2, 2, 3],
[1, 4, 4, 2],
[2, 4, 1, 3],
[2, 3, 2, 4]])
np.where(arr == 4, 1, 0)
Output:
array([[1, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]])
Upvotes: 1
Reputation: 1939
import numpy as np
matrix = np.zeros((5,5))
matrix[0]=[1,-2,3,4,-5]
matrix[2]=[0,1,4,0,4]
matrix=np.array([[1 if value==4 else 0 for value in row ] for row in matrix])
The above snippet uses nested list comprehension & than converts list back to np array
Upvotes: 0
Reputation: 528
arr = np.array([[4, 2, 2, 3],
[1, 4, 4, 2],
[2, 4, 1, 3],
[2, 3, 2, 4]])
In[58]: (arr==4).astype(int)
Out[58]: array([[1, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1]])
Upvotes: 2