如何区分np.ndarray或None?

时间:2017-09-19 12:21:29

标签: python python-3.x

有代码:

import numpy as np

def check(x):
    if x == None:
        print('x is None')

check(np.array([1,2]))

x可以是None或np.ndarray,所以我想检查x是否为无或np.ndarray,但如果我将np.ndarray传递给check,它将会提出错误, 因为np.ndarray ==无应使用np.any()np.all()。那我该怎么办?

3 个答案:

答案 0 :(得分:1)

试试这个:

import numpy as np

def check(x):
    if type(x) is np.ndarray:
        print('x is numpy.ndarray')
    else:
        raise ValueError("x is None")

check(np.array([1, 2]))

答案 1 :(得分:1)

检查ndarray类型

首选type(x):使用isinstance

来自PEP 8

  

对象类型比较应始终使用isinstance()而不是。{   直接比较类型。

在您的示例中:使用if isinstance(x, np.ndarray):

检查x是否为None

选项1: 使用elif x is None:。这明确检查x是否为无。

选项2: 使用elif not x:。这利用了None的“Falsiness”,但是如果x是其他“Falsey”值,例如np.nan,则它也会评估为True ,或空数据结构。

答案 2 :(得分:0)

它引发值错误的原因是,对于Numpy的最新版本,即使与None进行比较,__eq__数组覆盖也会进行元素对象比较。

使用Numpy 1.12.1:

In [2]: if np.array([1,2,3]) == None:
   ...:     print('Equals None')
   ...: else:
   ...:     print('Does not equal None')
   ...:     
/home/user/Work/SO/bin/ipython:1: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
  #!/home/user/Work/SO/bin/python3
Does not equal None

和Numpy 1.13.1:

In [1]: if np.array([1,2,3]) == None:
   ...:     print('Equals None')
   ...: else:
   ...:     print('Does not equal None')
   ...:     
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-06133f6732e1> in <module>()
----> 1 if np.array([1,2,3]) == None:
      2     print('Equals None')
      3 else:
      4     print('Does not equal None')
      5 

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

错误非常自我解释。与纯Python序列的行为相比,Numpy对数组的真实性有不同的看法。

为了检查某个对象是否为singleton value None,您应该使用identity comparison,并解释here

def check(x):
    if x is None:
        print('x is None')

    else:
        print('x is not None')