如何检查numpy.array是否存在? numpy数组的真值测试值吗?

问题描述

在开发使用numpy.array的类时,我想在一个阶段构造此数组,然后再检查它是否存在以便操纵它,或者在以后的阶段构造它(伪代码)下面)。我如何检查该数组是否存在?

对于任何基本对象,我使用:if my_object: # do something,它使用truth value testing,但是对于numpytruth value testing检查是否存在数组的任何或所有元素,因此if my_array: # do something显示错误The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

目前,唯一可行的方法调用isinstance(my_array,numpy.ndarray),但我认为这并不方便(特别是因为某些sklearn之类的库可以将numpy数组转换为{{1} }对象)。

用于说明我想做什么的伪代码

scipy.sparse

目前,我发现检查 def compute_my_array(self,...): # long job here return my_array def new_computation(self,my_array = None,...): if not my_array: # if my_array does not exist,compute it ... my_array = compute_my_array(self,...) do_something_else_with_my_array(my_array) # ... otherwise use it 是否存在的唯一方法是使用

my_array

还有其他(也许更好)的方法来进行检查吗?

解决方法

只需更改默认值即可返回一个空数组,然后检查数组中是否有任何东西

def new_computation(self,my_array = np.zeros((1,)),...):
   if not my_array.any(): # if my_array has no nonzero data,compute it ...
      my_array = compute_my_array(self,...)
   do_something_else_with_my_array(my_array) # ... otherwise use it