1

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

2
  • 2
    np.array([a,b])? Commented Sep 22, 2022 at 16:34
  • Empty and append work for lists. Don't try to copy that model with arrays. Lists have one dimension, you want a 2d array. np.array([]) is not an 'empty' array Pay attention to ita dimension. Commented Sep 22, 2022 at 23:11

2 Answers 2

1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

this is what i get when i try this on an empty numpy array, ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 8
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.