Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshaping arrays in an array of arrays

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?

like image 409
oxtay Avatar asked Sep 14 '25 11:09

oxtay


2 Answers

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.

like image 70
hpaulj Avatar answered Sep 17 '25 01:09

hpaulj


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.

like image 20
NeStack Avatar answered Sep 17 '25 02:09

NeStack