【问题标题】:How to check whether a numpy.array exists or not ? Truth testing value for numpy array?如何检查 numpy.array 是否存在? numpy数组的真值测试值?
【发布时间】:2020-10-27 09:14:39
【问题描述】:

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

对于任何基本对象,我使用:if my_object: # do something,它使用truth value testing,但对于numpytruth value testing 检查数组的任何或所有元素是否存在,因此if my_array: # do something 给出错误@ 987654328@.

目前,唯一可行的方法是调用isinstance(my_array,numpy.ndarray),但我认为这不是很方便(特别是因为像sklearn 这样的一些库可以将numpy 数组转换为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是否存在的唯一方法是使用

   if not isinstance(my_array, numpy.ndarray):
      my_array = compute_my_array(my_array)

还有其他(可能更好)的方法来做这个检查吗?

【问题讨论】:

  • 显然,if my_array is not None 完成了这项工作……还有更多的 Python 方法来解决这个问题吗?
  • if my_array is None: (这就是你想要的)是完美的pythonic
  • @DanielF 是的,但我的主要问题是 numpy 数组或 scipy.sparse 矩阵是否为空,所以这不是同一个问题。但我当然可以使用这个技巧。谢谢。
  • @amzon-ex 感谢您指向此答案。它并没有真正解决我的问题,因为我想知道一个可能是 scipy.sparse 或 numpy.array 的对象是否为空。但是,是的,尽管 object.shape 检查可以是一个选项。不过,我正在寻找更直接的东西。

标签: python numpy scipy isinstance


【解决方案1】:

只需更改默认返回一个空数组,然后检查数组中是否有任何内容

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

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 2020-03-15
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多