简体   繁体   English

如何区分np.ndarray或None?

[英]How to distinguish np.ndarray or None?

There is the code: 有代码:

import numpy as np

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

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

x can be None or np.ndarray, so I want to check whether x is None or np.ndarray, but if I pass np.ndarray into check , it will raise a error, because np.ndarray==None should use np.any() or np.all() . x可以是None或np.ndarray,所以我想检查x是None还是np.ndarray,但是如果我将np.ndarray传递给check ,它将引发错误,因为np.ndarray == None不应该使用np.any()np.all() So what should I do? 所以我该怎么做?

Try this one: 试试这个:

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]))

Checking for ndarray type 检查ndarray类型

Preferred over type(x) : use isinstance . 优先于type(x) :使用isinstance

From PEP 8 : PEP 8

Object type comparisons should always use isinstance() instead of comparing types directly. 对象类型比较应始终使用isinstance()而不是直接比较类型。

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

Checking if x is None 检查x是否为None

Option 1: Use elif x is None: . 选项1:使用elif x is None: This explicitly checks that x is None. 这将明确检查x是否为None。

Option 2: Use elif not x: . 选项2:使用elif not x: This takes advantage of the "Falsiness" of None , but it also would evaluate to True if x is other "Falsey" values such as np.nan , 0, or an empty data structure. 这利用了None的“虚假”优势, 但是如果x是其他“ Falsey”值(例如np.nan ,0或空的数据结构),它也将评估为True。

The reason it raises the value error is that with a recent enough version of Numpy the __eq__ override of arrays does an elementwise object comparison even when comparing to None. 它引起值错误的原因是,对于最新版本的Numpy,即使与None比较,数组的__eq__覆盖也会进行逐元素对象比较。

With Numpy 1.12.1: 使用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

and with Numpy 1.13.1: 以及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()

The error is quite self explanatory. 该错误很容易解释。 Numpy has a different view on truthiness of an array compared to how plain Python sequences behave. 与简单的Python序列的行为方式相比,Numpy对数组的真实性有不同的看法。

In order to check if an object is the singleton value None , you should use identity comparison as also explained here : 为了检查一个对象是单值没有 ,你应该使用的身份比较如还解释在这里

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

    else:
        print('x is not None')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM