Given a n-dimensional array with shape (N,d_1,...,d_{n-1}), I'd like to convert that array into a two dimensional array with shape (N,D), where D = \prod_i d_i. Is there any neat trick in numpy to do this?
1 Answer
You can use numpy.reshape() method , along with array.shape to get the shape of the original array and np.prod() to take the product of d_1 , d_2 , ... . Example -
In [22]: import numpy as np
In [23]: na = np.arange(10000).reshape((5,2,10,10,10))
In [26]: new_na = np.reshape(na, (na.shape[0], np.prod(na.shape[1:])))
In [27]: new_na.shape
Out[27]: (5, 2000)
Or a simpler version as suggested by @hpaulj in the comments -
In [31]: new_na = np.reshape(na, (na.shape[0], -1))
In [32]: new_na.shape
Out[32]: (5, 2000)
2 Comments
hpaulj
simpler still:
na.reshape(na.shape[0], -1)Anand S Kumar
Nice, I will add that to the answer if you do not mind?