Home > Software engineering >  How to make a 2d numpy array from an empty numpy array by adding 1d numpy arrays?
How to make a 2d numpy array from an empty numpy array by adding 1d numpy arrays?

Time:09-23

So I'm trying to start an empty numpy array with a = np.array([]), but when i append other numpy arrays (like [1, 2, 3, 4, 5, 6, 7, 8] and [9, 10, 11, 12, 13, 14, 15, 16] to this array, then the result im basically getting is
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16].

But what i want as result is: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]]

CodePudding user response:

IIUC you want to keep adding lists to your np.array. In that case, you can use something like np.vstack to "append" the new lists to the array.

a = np.array([[1, 2, 3],[4, 5, 6]])
np.vstack([a, [7, 8, 9]])

>>> array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

CodePudding user response:

You can also use np.c_[], especially if a and b are already 1D arrays (but it also works with lists):

a = [1, 2, 3, 4, 5, 6, 7, 8]
b = [9, 10, 11, 12, 13, 14, 15, 16]

>>> np.c_[a, b]
array([[ 1,  9],
       [ 2, 10],
       [ 3, 11],
       [ 4, 12],
       [ 5, 13],
       [ 6, 14],
       [ 7, 15],
       [ 8, 16]])

It also works "multiple times":

>>> np.c_[np.c_[a, b], a, b]
array([[ 1,  9,  1,  9],
       [ 2, 10,  2, 10],
       [ 3, 11,  3, 11],
       [ 4, 12,  4, 12],
       [ 5, 13,  5, 13],
       [ 6, 14,  6, 14],
       [ 7, 15,  7, 15],
       [ 8, 16,  8, 16]])
  • Related