Matlab isempty () function in numpy?

I have this code in matlab:

switch 1
    case isempty(A) 
...

where A is the dimension of a 2-dimensional array.

How can I check with numpy if 2-dim Array is empty (has only 0 values)?

+4
source share
3 answers

you can compare your array xwith 0 and see if all the values ​​are False

np.all(x==0)

+6
source

To verify that the array is empty (i.e. it does not contain any elements), you can use A.size == 0:

import numpy as np
In [2]: A = np.array([[1, 2], [3, 4]])

In [3]: A.size
Out[3]: 4

In [4]: B = np.array([[], []])

In [5]: B.size
Out[5]: 0

To check if it contains only 0, you can check np.count_nonzero(A):

In [13]: Y = np.array([[0, 0], [0, 0]])
In [14]: np.count_nonzero(Y)
Out[14]: 0
+5
source
>>> empty_array = np.zeros((3,3))
>>> empty_array
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> if np.all(empty_array==0): print True
... 
True
>>> empty_array[1][1]=1
>>> empty_array
array([[ 0.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  0.]])
>>> if np.all(empty_array==0): 
...    print True
... else:
...    print False
... 
False
0
source

All Articles