2

I have this array

     a = array([1,5,7])

I apply the where function

     where(a==8)

What is returned in this case is

    (array([], dtype=int64),)

However I would like the code to return the integer "0" whenever the where function returns an empty array. Is that possible?

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
Brian
  • 13,996
  • 19
  • 70
  • 94
  • 9
    What would you like it to return when there is a single match, and that match is at index zero? – NPE Jan 25 '12 at 12:32
  • 1
    Why do you want that? What is good for to have to return types? Why don't make a check of the array size to know if you found it? And then use the array in case it's not emtpy? – ezdazuzena Jan 25 '12 at 13:07
  • 1
    @aix: there is no possible "confusion" problem: if the match is at index 0, the result is `(array([0]),)`, not `0`. – Eric O. Lebigot Jan 25 '12 at 16:21

4 Answers4

5
def where0(vec):
    a = where(vec)
    return a if a[0] else 0
    # The return above is equivalent to:
    # if len(a[0]) == 0:
    #     return 0  # or whatever you like
    # else:
    #     return a

a = array([1,5,7])
print where0(a==8)

And consider also the comment from aix under your question. Instead of fixing where(), fix your algorithm

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Jakub M.
  • 32,471
  • 48
  • 110
  • 179
  • 1
    +1 for the general advice (it is best if functions only have a single return type), but your whole `if len(a[0]) == 0…` structure could be replaced by the much simpler and shorter `return a if a[0] else 0`. – Eric O. Lebigot Jan 25 '12 at 14:03
  • oh, I use python since long but never used this neat syntax... thanks! – Jakub M. Jan 25 '12 at 15:21
0

a empty array will return 0 with .size

import numpy as np    
a = np.array([])    
a.size
>> 0
Brad123
  • 877
  • 10
  • 10
0

Better use a function that has only one return type. You can check for the size of the array to know if it's empty or not, that should do the work:

 a = array([1,5,7])
 result = where(a==8)

 if result[0] != 0:
     doFancyStuff(result)
 else:
     print "bump"
ezdazuzena
  • 6,120
  • 6
  • 41
  • 71
-2

Try the below. This will handle the case where a test for equality to 0 will fail when index 0 is returned. (e.g. np.where(a==1) in the below case)

a = array([1,5,7])
ret = np.where(a==8)
ret = ret if ret[0].size else 0
Machavity
  • 30,841
  • 27
  • 92
  • 100
surfertas
  • 11
  • 4