Numpy array in array size

Let's say I create 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 the first column as a slice:

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

Let's say now I want to change the shape of 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 assume numpy treats every array in b as an object, not the array itself. The question is, is there a good way to make the desired resizing?

+4
source share
2 answers

In your specific example, you can 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 not a real matrix, but a collection of arrays (as indicated by wim), you can also do the following:

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

You cannot change form b in place, but you will create a copy of the desired form using np.vstack(b) . You probably already knew that.

Note that you did not make an array in the first column of a , if you check type(a[0,0]) , you will see that you actually have a list. those. your slice a[:,0] is actually a column vector of two list objects, it is not (and never was) an array in itself.

+2
source

Source: https://habr.com/ru/post/1441809/


All Articles