Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to append 2 2d arrays in numpy

Tags:

python

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?

like image 789
Delta_Fore Avatar asked Sep 12 '25 20:09

Delta_Fore


1 Answers

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]])
like image 112
toine Avatar answered Sep 15 '25 08:09

toine