问题:如何检查numpy数组是否为空?

如何检查numpy数组是否为空?

我使用了以下代码,但是如果数组包含零,则此操作将失败。

if not self.Definition.all():

这是解决方案吗?

if self.Definition == array( [] ):

How can I check whether a numpy array is empty or not?

I used the following code, but this fails if the array contains a zero.

if not self.Definition.all():

Is this the solution?

if self.Definition == array( [] ):

回答 0

您可以随时查看.size属性。它定义为一个整数,并且0在数组中没有元素时为零():

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

if a.size == 0:
    # Do something when `a` is empty

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

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

if a.size == 0:
    # Do something when `a` is empty

回答 1

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy的主要对象是齐次多维数组。在Numpy中,尺寸称为轴。轴数为等级。Numpy的数组类称为ndarray。别名数组也知道它。ndarray对象的更重要的属性是:

ndarray.ndim
数组的轴数(尺寸)。在Python世界中,维数称为等级。

ndarray.shape
数组的尺寸。这是一个整数元组,指示每个维度中数组的大小。对于具有n行和m列的矩阵,形状将为(n,m)。因此,形状元组的长度为ndim的等级或维数。

ndarray.size
数组元素的总数。这等于形状元素的乘积。

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy’s main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy’s array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.


回答 2

不过,请注意。请注意,np.array(None).size返回1!这是因为a.size 等于 np.prod(a.shape),np.array(None).shape是(),空乘积是1。

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

因此,我使用以下命令测试numpy数组是否具有元素:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

回答 3

我们为什么要检查数组是否为empty?数组不会像列表一样增长或缩小。从“空”数组开始,然后与之一起成长np.append是一个常见的新手错误。

使用列表if alist:取决于其布尔值:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

但是尝试对数组执行相同操作会产生(在版本1.18中):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

bool(np.array([1,2])产生臭名昭著的歧义错误。

Why would we want to check if an array is empty? Arrays don’t grow or shrink in the same that lists do. Starting with a ’empty’ array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。