Numpy.array with elements of different shapes

I want to have a numpy array of two other arrays (each with a different shape). As I know, for this reason one should use: dtype = object

in the definition of the main array.

For example, let's define (in Python 2.7) our arrays as

     a0 = np.arange(2*2).reshape(2,2)
     a1 = np.arange(3*3*2).reshape(3,3,2)
     b = np.array([a0,a1], dtype = object)

      

This works great: is the b[1]

same as a1

. But if I change the dimension a0

from (2.2) to (3.3), something strange happens:

     a0 = np.arange(3*3).reshape(3,3)
     a1 = np.arange(3*3*2).reshape(3,3,2)
     b = np.array([a0,a1], dtype = object)

      

At this time, b[1]

and a1

are not equal, they even have a different shape. What is the reason for this strange behavior?

Perhaps there is a completely different solution for me. But I don't want to use lists or tuples because I want to allow addition, eg b + b

. It is clear that I can write my own class for this purpose, but is there an easier way?

+3


source to share


2 answers


If you explicitly want an array of objects, you can first create an empty array with an object of type and assign to it:

x = empty(5, dtype=object)
x[0] = zeros((3,3))
x[1] = zeros((3,2)) #does not merge axes.
x[2] = eye(4)
x[3] = ones((2,2))*2
x[4] = arange(10).reshape((5,2))

>>> x+x
array([array([[ 0.,  0.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  0.,  0.]]),
   array([[ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.]]),
   array([[ 2.,  0.,  0.,  0.],
   [ 0.,  2.,  0.,  0.],
   [ 0.,  0.,  2.,  0.],
   [ 0.,  0.,  0.,  2.]]),
   array([[ 4.,  4.],
   [ 4.,  4.]]),
   array([[ 0,  2],
   [ 4,  6],
   [ 8, 10],
   [12, 14],
   [16, 18]])], dtype=object)

      



You will need to fill in all the elements before you can do arithmetic, or increment the element from zero to zero using np.append.

+2


source


I don't think this is weird behavior, this is how you use numpy, which is strange to me.

numpy concatenates size as much as it can. This is the default behavior and is expected when working with arrays. In the first example, all sizes a0

and are a1

different. numpy is forced to use only the first dimension. Therefore, if we look at b.shape

in the first example, we will see (2,)

.



In the second example a0

, and a1

have the same size of the size up to the last measurement. So numpy brings these levels together. If you look at b.shape

here, you will see (2,3,3)

since the second and third measurements are the same size.

+3


source







All Articles