Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.array with elements of different shapes

I want to have a numpy array of two another arrays (each of them has different shape). As I know, for this reason one must use: dtype = object in the definition of the main array.

For example, let us 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 perfect: b[1] is the same as a1. But if I change the dimension in 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)

This time b[1] and a1 are not equal, they even have different shapes. What is the reason of 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 such as b + b. It is clear that I can write my own class for this purpose but is there any simpler way?

like image 775
cheyp Avatar asked Oct 19 '14 17:10

cheyp


People also ask

Can NumPy contain elements of different types?

Yes, if you use numpy structured arrays, each element of the array would be a "structure", and the fields of the structure can have different datatypes.

Can NumPy array contains different data types?

Can an array store different data types? Yes, a numpy array can store different data String, Integer, Complex, Float, Boolean.


1 Answers

If you explicitly want an objects array, you can create an empty array with type object first 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 have to fill all elements before you can perform arithmetic, or grow the element from size zero using np.append.

like image 200
mdurant Avatar answered Oct 10 '22 20:10

mdurant