numpy array in array resize - Python

TAGS :
Viewed: 9 - Published at: a few seconds ago

[ numpy array in array resize ]

Say I make a weird little array:

``````&gt;&gt;&gt; a = np.array([[[1,2,3],4],[[4,5,6],5]])
&gt;&gt;&gt; a
array([[[1, 2, 3], 4],
[[4, 5, 6], 5]], dtype=object)
``````

And then take a the first column as a slice:

``````&gt;&gt;&gt; b = a[:,0]
&gt;&gt;&gt; b
array([[1, 2, 3], [4, 5, 6]], dtype=object)
&gt;&gt;&gt; b.shape
(2,)
``````

Say I now want to reshape b so that its shape is (2,3):

``````&gt;&gt;&gt; b.reshape((-1,3))
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ValueError: total size of new array must be unchanged
``````

I presume that numpy is treating each array in b as an object rather than an array in and of itself. The question is, is there a good way of doing the desired resize?

In your particular example, you could use numpy.vstack :

``````import numpy as np

a = np.array([[[1,2,3],4],[[4,5,6],5]])
b = a[:,0]

c = np.vstack(b)
print c.shape # (2,3)
``````

EDIT : Since your array `a` is not a real matrix but a collection of arrays (as pointed by wim ), you can also do the following :

``````   b = np.array([ line for line in a[:,0]])
print b.shape #(2,3)
``````

You can not change the shape of `b` in place, but you create a copy of the desired shape with `np.vstack(b)`. I guess you probably already knew this much though.
Note that you did not make an array in the first column of `a`, if you examine `type(a[0,0])` you will see that you actually have a list there. i.e. your slice `a[:,0]` is actually a column vector of two list objects, it isn't (and was never) an array in and of itself.