Where function in python returns nothing

北慕城南 提交于 2020-01-15 06:01:13

问题


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?


回答1:


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




回答2:


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"



回答3:


a empty array will return 0 with .size

import numpy as np    
a = np.array([])    
a.size
>> 0



回答4:


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


来源:https://stackoverflow.com/questions/9002749/where-function-in-python-returns-nothing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!