Cómo aplanar solo algunas dimensiones de una matriz numpy


¿Hay una forma rápida de "sub-aplanar" o aplanar solo algunas de las primeras dimensiones en una matriz numpy?

Por ejemplo, dada una matriz numpy de dimensiones (50,100,25), las dimensiones resultantes serían (5000,25)

Author: Eric Leschinski, 2013-09-12

3 answers

Echa un vistazo a numpy.remodelar .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)
 75
Author: Alexander,
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-10-04 10:52:54

Una ligera generalización a la respuesta de Alexander - np.reshape puede tomar -1 como argumento, lo que significa "tamaño total de la matriz dividido por el producto de todas las demás dimensiones enumeradas":

Por ejemplo, para aplanar todo menos la última dimensión:

>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
 62
Author: Peter,
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-10-24 18:14:30

Una ligera generalización a la respuesta de Peter can puede especificar un rango sobre la forma de la matriz original si desea ir más allá de las matrices tridimensionales.

Por ejemplo, para aplanar todas menos las últimas dos dimensiones:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

EDITAR: Una ligera generalización a mi respuesta anterior can puede, por supuesto, también especificar un rango al comienzo de la de la remodelación también:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)
 12
Author: KeithWM,
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-12-11 12:31:22