Delta_Fore
Delta_Fore

Reputation: 3271

Want to append 2 2d arrays in numpy

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?

Upvotes: 4

Views: 7446

Answers (2)

FarmerGedden
FarmerGedden

Reputation: 1201

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.

Upvotes: 0

toine
toine

Reputation: 2016

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]])

Upvotes: 4

Related Questions