Monday 15 June 2015

python - numpy.array with elements of different shapes -



python - numpy.array with elements of different shapes -

i want have numpy array of 2 arrays (each of them has different shape). know, reason 1 must use: dtype = object in definition of main array.

for example, allow 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] same a1. if alter dimension in a0 (2,2) (3,3) unusual 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] , a1 not equal, have different shapes. reason of unusual behavior?

perhaps there different solution me. don't want utilize lists or tuples because want allow add-on such b + b. clear can write own class purpose there simpler way?

if explicitly want objects array, can create empty array type object first , assign 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 have fill elements before can perform arithmetic, or grow element size 0 using np.append.

python arrays numpy

No comments:

Post a Comment