0

I'm attempting to use the itemfreq() function from scipy to count the frequencies of unique elements in numpy arrays.

Basically, I've declared a variable (let's call it "A") that outputs a numpy array. Depending on earlier inputs, "A" may contain anywhere from 0 to 13 elements. When "A" contains at least 1 element, the itemfreq() functions works perfectly, but if "A" is empty, I get the following error:

IndexError: index out of bounds.

I'd like to be able to write a simple statement like this:

if A = []: print ("Sorry, your array is empty")
else: print (itemfreq(A))

But I'm not sure how to say that first line of code ("if A is an empty array") in python-speak.

Thanks!

ali_m
  • 71,714
  • 23
  • 223
  • 298
Tom
  • 21
  • 1
  • 1
    `if not A` would do the trick – R Nar Nov 17 '15 at 20:57
  • Use try ... except ... – Loïc G. Nov 17 '15 at 20:58
  • 2
    `scipy.stats.itemfreq([])` happily returns me a `(0, 2)` empty array (using either scipy v0.14.1 or v0.16.1). Perhaps the exception is being raised somewhere else - could you show the full traceback in your question? – ali_m Nov 17 '15 at 21:15
  • 1
    If you can, update scipy to a newer version. The error you're getting was fixed in 0.14; the latest released version of scipy is 0.16.1. You can check the version you have with `import scipy; print scipy.__version__`. – Warren Weckesser Nov 17 '15 at 22:28

3 Answers3

0

Catch exception with try ... except clause :

try:
    print(itemfreq(A))
except IndexError:
    print("Sorry, your array is empty")

You should prefer try-except over an if/else

Better to 'try' something and catch the exception or test if its possible first to avoid an exception?

Using try vs if in python

Community
  • 1
  • 1
Loïc G.
  • 3,087
  • 3
  • 24
  • 36
0

I would formulate it as

if len(A) == 0:
    print ("Sorry, your array is empty")

or

try:
    print (itemfreq(A))
except LookupError:
    print ("Sorry, your array is empty")
Vadim
  • 633
  • 1
  • 8
  • 17
0

Empty list/arrays have zero length:

if len(A) == 0:
    print ("Sorry")
Bendik
  • 1,097
  • 1
  • 8
  • 27