python - 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)
解决方案
当您向 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')
推荐阅读
- jquery - Summernote 设置不好
- react-native - React Native 视频构建失败
- dreamweaver - 织梦者 | 动态相关文件 | 显示除 .php 文件之外的所有文件
- python - 进行矢量化计算时如何处理 typeErrors?
- python - 为什么如果我想添加另一个显示消息错误“预期缩进错误”的函数
- javascript - 添加具有唯一 ID 的新字段
- android - Android SpeechRecognizer 类可以识别音节/电话,而不仅仅是完整的单词吗?
- python - 我无法更新数组中的变量
- android - 自定义布局未使用约束布局在列表视图中居中
- python-3.x - 如何在具有功能的tkinter中显示多张图片?