1

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.

2
  • 2
    Just (array==4).astype(int)? Commented Jun 10, 2020 at 13:31
  • Yes simple as that. Commented Jun 10, 2020 at 13:41

3 Answers 3

2
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]])
Sign up to request clarification or add additional context in comments.

Comments

1

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]])

1 Comment

This is also good and fast, but the accepted answer is like 5% faster
0
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])

enter image description here

The above snippet uses nested list comprehension & than converts list back to np array

1 Comment

Yes this gets the job done well for a 2d or 3d matrix, but the use of for loops take a long time to compute. My array is pretty big. The other answer is better in my case.

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.