1

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 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

simpler still: na.reshape(na.shape[0], -1)
Nice, I will add that to the answer if you do not mind?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.