如何创建全部为True或全部为False的numpy数组? [英] How to create a numpy array of all True or all False?

查看:993
本文介绍了如何创建全部为True或全部为False的numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如何创建一个由所有True或False填充的任意形状的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))

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

这篇关于如何创建全部为True或全部为False的numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆