eager2learn
eager2learn

Reputation: 1488

Numpy Convert N dimensional array into two dimensional array

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?

Upvotes: 1

Views: 3138

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90879

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)

Upvotes: 3

Related Questions