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?
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 an array store different data types? Yes, a numpy array can store different data String, Integer, Complex, Float, Boolean.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With