且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建全部为True或全部为False的numpy数组?

更新时间:2023-11-27 22:55:58

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))

由于TrueFalse在Python中分别表示为10,我们只需要使用可选的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 ,我们可以使用full来实现相同的语法结果更清楚地表明了我们的意图(正如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)