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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21174961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:13:13  来源:igfitidea点击:

How to create a numpy array of all True or all False?

pythonarraysnumpybooleannumpy-ndarray

提问by Michael Currie

In Python, how do I create a numpy array of arbitrary shape filled with all True or all False?

在 Python 中,如何创建一个填充所有 True 或全部 False 的任意形状的 numpy 数组?

采纳答案by Michael Currie

numpy already allows the creation of arrays of all ones or all zeros very easily:

numpy 已经允许非常轻松地创建全 1 或全 0 的数组:

e.g. numpy.ones((2, 2))or numpy.zeros((2, 2))

例如numpy.ones((2, 2))numpy.zeros((2, 2))

Since Trueand Falseare represented in Python as 1and 0, respectively, we have only to specify this array should be boolean using the optional dtypeparameter and we are done.

由于TrueandFalse在 Python 中分别表示为1and 0,我们只需要使用可选dtype参数指定这个数组应该是布尔值,我们就完成了。

numpy.ones((2, 2), dtype=bool)

numpy.ones((2, 2), dtype=bool)

returns:

返回:

array([[ True,  True],
       [ True,  True]], dtype=bool)

UPDATE: 30 October 2013

更新:2013 年 10 月 30 日

Since numpy version 1.8, we can use fullto achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):

从 numpy版本 1.8 开始,我们可以使用full更清楚地显示我们意图的语法来实现相同的结果(正如 fmonegaglia 指出的那样):

numpy.full((2, 2), True, dtype=bool)

numpy.full((2, 2), True, dtype=bool)

UPDATE: 16 January 2017

更新:2017 年 1 月 16 日

Since at least numpy version 1.12, fullautomatically casts results to the dtypeof the second parameter, so we can just write:

由于至少 numpy版本 1.12full自动将结果转换dtype为第二个参数的,所以我们可以只写:

numpy.full((2, 2), True)

numpy.full((2, 2), True)

回答by user2357112 supports Monica

onesand zeros, which create arrays full of ones and zeros respectively, take an optional dtypeparameter:

oneszeros,分别创建充满 1 和 0 的数组,采用一个可选dtype参数:

>>> numpy.ones((2, 2), dtype=bool)
array([[ True,  True],
       [ True,  True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
       [False, False]], dtype=bool)

回答by fmonegaglia

numpy.full((2,2), True, dtype=bool)

回答by nikithashr

>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)

numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

numpy.full(大小,标量值,类型)。还有其他参数可以传递,有关文档,请查看https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

回答by MSeifert

If it doesn't have to be writeable you can create such an array with np.broadcast_to:

如果它不必是可写的,您可以使用以下命令创建这样一个数组np.broadcast_to

>>> import numpy as np
>>> np.broadcast_to(True, (2, 5))
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

If you need it writable you can also create an empty array and fillit yourself:

如果您需要它可写,您还fill可以自己创建一个空数组:

>>> arr = np.empty((2, 5), dtype=bool)
>>> arr.fill(1)
>>> arr
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

These approaches are only alternative suggestions. In general you should stick with np.full, np.zerosor np.oneslike the other answers suggest.

这些方法只是替代建议。一般来说,您应该坚持使用np.fullnp.zeros或者np.ones像其他答案所建议的那样。

回答by Joschua

Quickly ran a timeit to see, if there are any differences between the np.fulland np.onesversion.

赶紧跑个timeit看看,np.fullnp.ones版本有没有区别。

Answer: No

答案:没有

import timeit

n_array, n_test = 1000, 10000
setup = f"import numpy as np; n = {n_array};"

print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")

Result:

结果:

np.ones: 0.38416870904620737s
np.full: 0.38430388597771525s


IMPORTANT


重要的

Regarding the post about np.empty(and I cannot comment, as my reputation is too low):

关于帖子np.empty(我无法发表评论,因为我的声誉太低):

DON'T DO THAT. DON'T USE np.emptyto initialize an all-Truearray

不要那样做。不要np.empty用于初始化全True数组

As the array is empty, the memory is not written and there is no guarantee, what your values will be, e.g.

由于数组为空,因此不会写入内存并且无法保证您的值是什么,例如

>>> print(np.empty((4,4), dtype=bool))
[[ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]
 [ True  True False False]]