1

How do I test if a numpy array is empty. I have problem if the there is only one element with value 0. If I do

a = np.array([0])
a.any()

results is False while

a = np.array([1])
a.any()

is True So how do I check np.array has no elements?

Bruno Vermeulen
  • 2,970
  • 2
  • 15
  • 29
  • 1
    Check if a.size == 0 should do the trick – ZaxR May 19 '20 at 04:46
  • at the moment I do `len(a) == 1` to capture the only element with value 0. Better perhaps to use `a.size != 0` – Bruno Vermeulen May 19 '20 at 04:55
  • Checking the `size` makes most sense. But why why do you need to check this? Is this a 1d array? How is it created? – hpaulj May 19 '20 at 05:48
  • The future warning produced by `bool(np.array([]))` suggests using `array.size > 0`. – hpaulj May 19 '20 at 07:27
  • The array contains a list of index numbers where a value is duplicate in another list. If the array is not empty then I remove these elements. This worked all fine until I came across one where the index value was zero. – Bruno Vermeulen May 19 '20 at 07:39
  • `np.nonzero` (`np.where`) produces a tuple of indexing arrays. Those may be size 0 if nothing in the condition is True, – hpaulj May 19 '20 at 14:43

0 Answers0