Numpy np.where(condition is None)与np.where(condition == None)的区别

Numpy np.where(condition is None)与np.where(condition None)的区别

在本文中,我们将介绍Numpy中np.where(condition is None)与np.where(condition None)的区别。Numpy中的np.where(condition)用于从条件数组中获取元素的索引,其中condition可以是一个条件数组或一个布尔表达式。当condition为None时,np.where()将返回非零元素的索引。

阅读更多:Numpy 教程

np.where(condition is None)

当condition为None时,np.where(condition is None)将返回所有非零元素的索引,而不管它们的值是什么。例如:

import numpy as np

arr = np.array([1, 0, 2, 0, 3, 0])
idx = np.where(arr is None)

print(idx)  # 输出 (array([0, 1, 2, 3, 4, 5], dtype=int64),)
Python

我们可以看到,由于condition为None,np.where()返回了所有非零元素的索引。在本例中,数组arr中所有非零元素的索引都被返回。

np.where(condition None)

当condition为一个布尔表达式时,np.where(condition None)将返回符合条件的元素的索引。如果元素的值为None,则它将被视为False。例如:

import numpy as np

arr = np.array([1, None, 2, None, 3, None])
idx = np.where(arr == None)

print(idx)  # 输出 (array([1, 3, 5], dtype=int64),)
Python

我们可以看到,由于元素的值为None,np.where()返回了元素索引为1、3和5的数组。与之相反,如果我们想要返回确定元素的索引,我们可以改用如下代码:

import numpy as np

arr = np.array([1, None, 2, None, 3, None])
idx = np.where(arr is None)

print(idx)  # 输出 (array([], dtype=int64),)
Python

我们可以看到,由于condition为None,np.where()未能找到符合条件的元素,因此返回了一个空数组。

总结

本文介绍了Numpy中np.where(condition is None)与np.where(condition None)的区别。当condition为None时,np.where(condition is None)返回所有非零元素的索引,而np.where(condition None)返回符合条件的非零元素的索引。要根据元素的值返回索引,请使用np.where(condition value)。在处理None值时,请特别注意这种差异。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册