4

I have an array of 40 arrays, each with a 1x150 shape. Is there a way to reshape the arrays so that I have 40 arrays of 3x50 arrays?

I am not sure if there is a way to use np.reshape and just do it in one line, is there?

2
  • "I have an array of 40 arrays..." Is it actually a 3D array with shape (40, 1, 150), or is it a 1D array with dtype "object" (with the objects being arrays with shape (1, 150))? Commented Jul 23, 2014 at 3:43
  • It is the later, a 1D array with dtype=object Commented Jul 24, 2014 at 16:43

2 Answers 2

8

Is this really an array of np.arrays, or a list of those arrays? If it is an array, what is its shape and dtype?

If it is a list, or array with dtype=object, then you have to iterate over items, and reshape each one.

 [a.reshape(3,50) for a in A]

If you have a 3d array, its shape may be (40, 1, 150).

 A.reshape(40, 3, 50)

Since the items in an 'object' array could be anything - strings, arrays, lists, dict - there can't be a reshape that applies to all of them 'at once'. Even if they are all arrays, they could each have different dimensions. In fact that is usually how an array of arrays is produced.

In [5]: np.array([[1,2,3],[2,3]])
Out[5]: array([[1, 2, 3], [2, 3]], dtype=object)

You have to take special steps to construct an object array with items that all have the same shape. np.array tries to construct the highest dimensional array it can.

In [7]: A=np.empty((2,),dtype=object)
In [8]: A[0] = np.array([1,2,3])
In [9]: A[1] = np.array([4,5,6])
In [10]: A
Out[10]: array([array([1, 2, 3]), array([4, 5, 6])], dtype=object)

Another way to look at it: reshape just changes an attribute of the array. It does nothing to the data. In the case of a 3d array, there is one shape value, and one block of data.

But in the array of objects, each object has its own shape and data.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply. It is an array with dtype=object and I know I could iterate over them. I should've probably been more clear in clarifying what I mean by "one line". I was curious in knowing if a version of reshape function exists that would do this.
I added some notes on the dtype=object case.
5

For reshaping a numpy-array containing numpy-arrays I found this contribution helpful - you can first use b=np.hstack(array_of_arrays) to create a flattened 1D numpy-array, and then just reshape b.

Comments

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.