Reputation: 14846
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?
Upvotes: 2
Views: 5935
Reputation: 944
a empty array will return 0 with .size
import numpy as np
a = np.array([])
a.size
>> 0
Upvotes: 0
Reputation: 11
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
Upvotes: -2
Reputation: 6800
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"
Upvotes: 0
Reputation: 33877
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
Upvotes: 5