2

Having an empty array

x = numpy.empty(0)

And two lists that looks like this

l1 = [1, 2, 3]
l2 = [4, 5, 6]

how do i add to the empty array the lists so that it becomes something like this

np.array([[1, 2, 3], [4, 5, 6])

instead of

np.array([1, 2, 3, 4, 5, 6])

which is what happens when i use

x = np.append(x, l1)
x = np.append(x, l2)
4
  • 4
    You could simply do x = np.array([l1, l2]), and in case you need to append frequently, I would suggest appending it to a list and then convert to array when you need to. np.append is more expensive that list.append. Commented May 19, 2020 at 11:18
  • 1
    What is your use-case, why are you defining x = numpy.empty(0) in the first place? Commented May 19, 2020 at 11:26
  • FWIW, if you want to use np.append the code will be: x = np.empty((0,3));x = np.append(x, [l1], axis=0);x = np.append(x, [l2], axis=0) Commented May 19, 2020 at 11:54
  • You didn't read the append docs carefully.enough! Commented May 19, 2020 at 14:17

4 Answers 4

4

Simply use np.vstack to stack arrays in sequence vertically:

l1 = [1, 2, 3]
l2 = [4, 5, 6]


x = np.vstack([l1, l2])
print(x)

This results:

array([[1, 2, 3],
       [4, 5, 6]])
Sign up to request clarification or add additional context in comments.

Comments

3
import numpy as np

x = []
l1 = [1, 2, 3]
l2 = [4, 5, 6]

x.append(l1)
x.append(l2)

x = np.array(x)
print(x)

Comments

0

First of all convert the lists to numpy arrays to work more flexible

from numpy import *
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l1_np = asarray(l1)
l2_np = asarray(l2)
l = concatenate([l1_np,l2_np])

Comments

0

You could use reshape to help make the append operation automatically

l1 = np.array([1, 2, 3])
l2 = np.array([4, 5, 6])
l=np.concatenate([l1,l2])
l.reshape((2,3))

outputs:

array([[1, 2, 3],
       [4, 5, 6]])

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.