7

I have this code in matlab:

switch 1
    case isempty(A) 
...

where A is a 2 dimension Array.

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

gustavgans
  • 5,141
  • 13
  • 41
  • 51
  • 1
    This is quite a late comment but I just came to this question trying to translate some matlab code to python. There is a wrong assumption in the question (at least for nowadays way of functioning matlab): `isempty()` does NOT check for 'only contains zeros' but for 'at least on dimension is length zero' (), meaning A has no content. Thus the answer is rather `A.size == 0` as posted here: https://stackoverflow.com/questions/11295609/how-can-i-check-whether-the-numpy-array-is-empty-or-not – NicoH Nov 15 '19 at 17:20

3 Answers3

10

For checking if an array is empty (that is, it doesn't 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 whether it only contains 0's you can check for np.count_nonzero(A):

In [13]: Y = np.array([[0, 0], [0, 0]])
In [14]: np.count_nonzero(Y)
Out[14]: 0
tttthomasssss
  • 5,852
  • 3
  • 32
  • 41
  • Thanks. I think the matlab code is trying to find out with isempty() if the array only includes 0. So size would not work I guess. So I try your second one :) – gustavgans Nov 28 '14 at 09:05
6

you can compare your array x, with 0 and see if all values are False

np.all(x==0)

bakkal
  • 54,350
  • 12
  • 131
  • 107
0
>>> 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
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36