-1

I have a list(Y) which contains numpy arrays of different length.The list contain more than 50 element(I just took five for testing).The shape of the list is 5 and I can print the shape of each element as shown below and the outputs are in the comments

print(Y.shape) #(5,)
print(Y[0].shape) #(600, 2)
print(Y[1].shape) #(250, 2)
print(Y[2].shape) #(300, 2)
print(Y[3].shape) #(200, 2)
print(Y[4].shape) #(100, 2)

each element of the list has different length(600,250,300,200,100) but all have [1 0] or [0 1] dimension.I want to add these elements and get output as

(1450,2)

I have tried

Y=np.sum(Y, axis=0)

it gives a broadcast error,ValueError: operands could not be broadcast together with shapes (600,2) (250,2) and I know this wants (600,2) (600,2) or (250,2) (250,2) but I want to add the 600 and 250.

The same function works with a three dimension array like [80,20,30] and [40,20,30] I get output as [120,20,30]

how can I add/sum these elements?

dm5
  • 350
  • 1
  • 6
  • 18

1 Answers1

1

Use np.concatenate:

np.concatenate(Y, axis=0)

For example:

import numpy as np

Y1 = np.ones((100, 2))
Y2 = np.ones((200, 2))
Y3 = np.ones((300, 2))

np.concatenate([Y1, Y2, Y3], axis=0).shape   # (600, 2)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 2
    If Y is a list as OP claims what is the point of your list comprehension [arr for arr in Y] ? – P. Camilleri Jun 08 '17 at 13:32
  • 1
    Y cannot be a np.array because Y[0] and Y[1] don't have the same shape. So Y is most probably a list and OP used Y.shape instead of len(Y). I think that the list comprehension is extraneous and a bit misleading. – P. Camilleri Jun 08 '17 at 13:39
  • But yes, it should work either way with just `Y`. So I'll remove my comments and I already updated the answer. Thanks for your feedback :) – MSeifert Jun 08 '17 at 13:43