如何创建一个全部为 True 或全部为 False 的 numpy 数组? [英] How to create a numpy array of all True or all False?
问题描述
在 Python 中,如何创建一个任意形状的 numpy 数组,其中填充全真或全假?
In Python, how do I create a numpy array of arbitrary shape filled with all True or all False?
推荐答案
numpy 已经允许非常容易地创建全 1 或全 0 的数组:
numpy already allows the creation of arrays of all ones or all zeros very easily:
例如numpy.ones((2, 2))
或 numpy.zeros((2, 2))
由于 True
和 False
在 Python 中分别表示为 1
和 0
,我们只需要使用可选的 dtype
参数指定这个数组应该是布尔值,我们就完成了.
Since True
and False
are represented in Python as 1
and 0
, respectively, we have only to specify this array should be boolean using the optional dtype
parameter and we are done.
numpy.ones((2, 2), dtype=bool)
返回:
array([[ True, True],
[ True, True]], dtype=bool)
更新:2013 年 10 月 30 日
由于 numpy 1.8 版,我们可以使用 fullcode> 使用更清楚地显示我们意图的语法来实现相同的结果(正如 fmonegaglia 指出的那样):
Since numpy version 1.8, we can use full
to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):
numpy.full((2, 2), True, dtype=bool)
更新:2017 年 1 月 16 日
至少从 numpy 1.12 版开始,full
自动将结果转换为第二个参数的 dtype
,所以我们可以这样写:
Since at least numpy version 1.12, full
automatically casts results to the dtype
of the second parameter, so we can just write:
numpy.full((2, 2), True)
这篇关于如何创建一个全部为 True 或全部为 False 的 numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!