Skip to main content
 首页 » 编程设计

python之异常相等性检查之使用 Numpy Where 查找抛出异常的索引

2025年05月04日8daizhj

有没有办法使用np.where找到抛出异常的索引? 例如:

a = np.array(['0.0', 'hi', '2012:13', '2013/04/05', '9.8', '7.6']) 
 
print np.where(np.float64(a)==Exception)[0][-1] 

我希望能提供这样的输出:

[ 0.  4.  5.] 

但是,它给出了这个输出:

ValueError: could not convert string to float: hi 

这个脚本可以提供答案,但它似乎效率很低,而且更不符合 pythonic:

b = np.array([]) 
for i, x in enumerate(a): 
    try: 
        np.float64(x) 
    except: 
        b = np.hstack((b,i)) 
print b 

请您参考如下方法:

你可以 define a function

def is_number(s): 
    try: 
        np.float64(s) 
        return True 
    except ValueError: 
        return False 

然后通过列表理解收集你的花车

print np.array([np.float64(x) for x in a if is_number(x)]) 

这是否在代码的可读性或紧凑性方面更好,将取决于您是否可以在代码的多个位置使用该函数。关于效率我希望这个解决方案对于大问题规模更快;因为我担心 hstack 有 O(len(b)) 复杂度,这意味着 O(len(b)**2)对于您当前拥有的脚本。