np.where(条件为None)不等于np.where(条件== None)

时间:2018-11-16 20:15:51

标签: python numpy

我对np.where()函数感到困扰。 (在我的示例中,第7行)

背景:我正在编写游戏“ Connect Four”。此insert_chip()方法访问变量self.board,它是我的个人dtype Chip的8x8 np数组。如果chip的条目中没有self.board,则值为None

由于某些原因,np.where(col_entries is None)不会返回None元素的索引。当我在条件中写col_entries == None时为什么收到不同的输出? None是否具有参考权?

def insert_chip(self, chip, col):
    # slices the entries of the column into a new array
    col_entries = self.board[:, col:col+1]

    # checks for all unoccupied pos in this col (entries are None)
    # gives double array of indexes with the form (array([row_i, ...]), array([col_i, ...]))
    none_indexes = np.where(col_entries is None)

    # the pos where the chip will fall is the one with the highest index
    self.board[len(none_indexes[0]), col] = chip

2 个答案:

答案 0 :(得分:4)

  

由于某些原因,np.where(col_entries is None)不会返回None元素的索引。

is运算符检查两个操作数是否指向相同的对象。因此,这里它检查col_entries(矩阵)是否为None,因此 not 不会执行“广播”以检查矩阵中的某些元素是否引用了{{1} }。

在Python中,人们可以重载None<=等某些运算符。Numpy可以利用它来实现特定的运算符,从而可以编写==来生成矩阵布尔值。 some_matrix == 0运算符不能 被重载,因此Numpy(以及任何其他库)都可以对此进行控制。 is仅检查两个操作数是否引用相同的对象。

由于这里的is引用了一个numpy数组,因此它将始终为col_entries,因此False将始终返回包含一个空数组的1元组。

尽管没有太多等于np.where(col_entries is None)的对象,但是依靠它仍然不是很安全。我们可以向量化None运算符,例如:

is

答案 1 :(得分:3)

制作对象dtype数组:

In [37]: arr = np.zeros((3,3), object)
In [39]: arr[range(3),range(3)]=None
In [40]: arr
Out[40]: 
array([[None, 0, 0],
       [0, None, 0],
       [0, 0, None]], dtype=object)

is None测试:

In [41]: arr is None
Out[41]: False

==测试。

In [42]: arr == None
Out[42]: 
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True]])
In [43]: np.where(arr == None)
Out[43]: (array([0, 1, 2]), array([0, 1, 2]))

比较测试在对象数组中的传播已经发生了一些变化。来自最近的release_notes:https://docs.scipy.org/doc/numpy-1.15.1/release.html#comparison-ufuncs-accept-dtype-object-overriding-the-default-bool


列表上的类似操作

In [44]: alist = [0,None,0]
In [45]: alist is None
Out[45]: False
In [46]: [i is None for i in alist]
Out[46]: [False, True, False]
In [48]: alist.index(None)
Out[48]: 1
相关问题