首页 > 解决方案 > ndarray 的布尔数组

问题描述

我有这个来自应用 numpy.any 的数组(我们称之为 my_array):

my_array
array([[ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       ...,
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True]])

有没有办法将此数组转换为ndarray?我的意思是,我怎么能看到这个:

array([[ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       ...,
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True]],dtype=bool)

标签: pythonnumpy

解决方案


当您向 IDE 显示类似的内容时,它会使用repr(obj),它会创建对象的字符串表示形式。理想情况下,这也意味着eval(repr(object)) == object. 您看不到该dtype=bool部分的原因是完全由布尔值组成的数组是明确的布尔值。同样,整数数组默认为 dtype int32,因此也被排除在外。但是如果你有一个其他类型的整数,那么它就会被显示出来。

>>> np.array([1, 2])
array([1, 2])
>>> np.array([1, 2]).dtype
dtype('int32')
>>> np.array([1, 2], dtype=np.uint8)
array([1, 2], dtype=uint8)

您的结果已经在您想要的输出中。numpy.any的文档确认:

Returns
-------
any : bool or ndarray
    A new boolean or `ndarray` is returned unless `out` is specified,
    in which case a reference to `out` is returned.

但是如果你想确保一切都正确,你可以检查type(my_array)and my_array.dtype(假设对象是一个 numpy 数组)。

>>> a = np.any([[1, 2], [3, 4]], axis=0)
>>> a
array([ True,  True])
>>> type(a)
<class 'numpy.ndarray'>
>>> a.dtype
dtype('bool')

推荐阅读