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

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

问题描述

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

由于 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 版,我们可以使用 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屋!

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