¿Cómo crear una matriz numpy de todo Verdadero o todo Falso?


En Python, ¿cómo puedo crear una matriz numpy de forma arbitraria llena de todo Verdadero o todo Falso?

Author: ziad mansour, 2014-01-17

5 answers

Numpy ya permite la creación de arrays de todos los unos o todos los ceros muy fácilmente:

Por ejemplo numpy.ones((2, 2)) o numpy.zeros((2, 2))

Dado que True y False se representan en Python como 1 y 0, respectivamente, solo tenemos que especificar que este array debe ser booleano usando el parámetro opcional dtype y hemos terminado.

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

Devuelve:

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

ACTUALIZACIÓN: 30 de octubre de 2013

Desde numpy versión 1.8, podemos usar full para conseguir el mismo resultado con sintaxis que muestra más claramente nuestra intención (como señala fmonegaglia):

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

ACTUALIZACIÓN: 16 de enero de 2017

Desde al menos numpy versión 1.12, full arroja automáticamente los resultados al dtype del segundo parámetro, por lo que podemos escribir:

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

 156
Author: Michael Currie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-26 06:49:04
numpy.full((2,2), True, dtype=bool)
 70
Author: fmonegaglia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-30 08:01:26

ones y zeros, que crean matrices llenas de unos y ceros respectivamente, toman un parámetro opcional 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)
 23
Author: user2357112,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 23:24:00

Si no tiene que ser escribible, puede crear dicho array con 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)

Si lo necesita escribible, también puede crear una matriz vacía y fill es usted mismo:

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

Estos enfoques son solo sugerencias alternativas. En general, usted debe seguir con np.full, np.zeros o np.ones como sugieren las otras respuestas.

 7
Author: MSeifert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-15 12:16:30
>>> 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 (Tamaño, Valor Escalar, Tipo). Hay otros argumentos también que se pueden pasar, para documentación sobre eso, marque https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

 -2
Author: nikithashr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-15 02:28:22