Reputation: 6582
Say I make a weird little array:
>>> a = np.array([[[1,2,3],4],[[4,5,6],5]])
>>> a
array([[[1, 2, 3], 4],
[[4, 5, 6], 5]], dtype=object)
And then take a the first column as a slice:
>>> b = a[:,0]
>>> b
array([[1, 2, 3], [4, 5, 6]], dtype=object)
>>> b.shape
(2,)
Say I now want to reshape b so that its shape is (2,3):
>>> b.reshape((-1,3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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?
Upvotes: 4
Views: 10995
Reputation: 11012
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)
Upvotes: 3
Reputation: 363566
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.
Upvotes: 2