3

I'm trying to append 2 2d numpy arrays

a = np.array([[1],
       [2],
       [3],
       [4]])

b = np.array([[ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

target is

c = ([[1],
       [2],
       [3],
       [4],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

Tried np.concatenate((a,b),axis=0) and np.concatenate((a,b),axis=1) and get

ValueError: all the input array dimensions except for the concatenation axis must match exactly

and np.append(a,b)

But nothing seems to work. If I convert to list it gives me the result I want but seems inefficient

c = a.tolist() + b.tolist()

Is there a numpy way to do this?

Delta_Fore
  • 3,079
  • 4
  • 26
  • 46
  • Nope, this is not possible. As you've said, you have two 2D arrays. What sort of array has a different number of columns in the first row than in the fifth row? Your second approach works because now you're just concatenating two lists. The fact that the lists both contain lists as elements doesn't matter in this context. Maybe you could fill the first rows up with zeros. – Carsten Jun 26 '14 at 13:18
  • It's an API that uses string based ragged arrays that I've got to use at work. – Delta_Fore Jun 26 '14 at 13:26

2 Answers2

4

As the error indicate, the dimensions have to match.

So you could resize a so that it matches the dimension of b and then concatenate (the empty cells are filled with zeros).

a.resize(3,4)
a = a.transpose()
np.concatenate((a,b))

array([[ 1,  0,  0],
       [ 2,  0,  0],
       [ 3,  0,  0],
       [ 4,  0,  0],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
toine
  • 1,946
  • 18
  • 24
  • Voted up due to best answer to a problem that's not quite solvable in numpy. I stuck to my list append answer – Delta_Fore Jun 26 '14 at 13:28
  • always best to stick with the 'correct' way of doing things, unless sufficient gain for not to. Here, the zeroes shouldn't be such a problem right. – toine Jun 26 '14 at 13:34
0

Short answer - no. Numpy arrays need to be 'rectangular'; similar to matrices in linear algebra. You can follow the suggestion here and force it in (at the loss of a lot of functionality) or, if you really need the target, use a data structure like a list which is designed to cope with it.

Community
  • 1
  • 1
FarmerGedden
  • 1,162
  • 10
  • 23