Numpy append list to array without merging them

Viewed 1278

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 Answers

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

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

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