Home » Python » Append a NumPy array to a NumPy array

# Append a NumPy array to a NumPy array

Questions:

I have a numpy_array. Something like `[ a b c ]`.

And then I want to append it into another NumPy array (just like we create a list of lists). How do we create an array of NumPy arrays containing NumPy arrays?

I tried to do the following without any luck

``````>>> M = np.array([])
>>> M
array([], dtype=float64)
>>> M.append(a,axis=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'append'
>>> a
array([1, 2, 3])
``````
``````In : import numpy as np

In : a = np.array([[1, 2, 3], [4, 5, 6]])

In : b = np.array([[9, 8, 7], [6, 5, 4]])

In : np.concatenate((a, b))
Out:
array([[1, 2, 3],
[4, 5, 6],
[9, 8, 7],
[6, 5, 4]])
``````

or this:

``````In : a = np.array([1, 2, 3])

In : b = np.array([4, 5, 6])

In : np.vstack((a, b))
Out:
array([[1, 2, 3],
[4, 5, 6]])
``````

Questions:

Well, the error message says it all: NumPy arrays do not have an `append()` method. There’s a free function `numpy.append()` however:

``````numpy.append(M, a)
``````

This will create a new array instead of mutating `M` in place. Note that using `numpy.append()` involves copying both arrays. You will get better performing code if you use fixed-sized NumPy arrays.

Questions:

Sven said it all, just be very cautious because of automatic type adjustments when append is called.

``````In : import numpy as np

In : a = np.array([1,2,3])

In : b = np.array([1.,2.,3.])

In : c = np.array(['a','b','c'])

In : np.append(a,b)
Out: array([ 1.,  2.,  3.,  1.,  2.,  3.])

In : a.dtype
Out: dtype('int64')

In : np.append(a,c)
Out:
array(['1', '2', '3', 'a', 'b', 'c'],
dtype='|S1')
``````

As you see based on the contents the dtype went from int64 to float32, and then to S1

Questions:

You may use `numpy.append()`

``````import numpy

B = numpy.array()
A = numpy.array([1, 2, 2])
B = numpy.append( B , A )

print B

> [3 1 2 2]
``````

This will not create two separate arrays but will append two arrays into a single dimensional array.

Questions:

Actually one can always create an ordinary list of numpy arrays and convert it later.

``````In : import numpy as np

In : a = np.array([[1,2],[3,4]])

In : b = np.array([[1,2],[3,4]])

In : l = [a]

In : l.append(b)

In : l = np.array(l)

In : l.shape
Out: (2, 2, 2)

In : l
Out:
array([[[1, 2],
[3, 4]],

[[1, 2],
[3, 4]]])
``````

Questions:

If I understand your question, here’s one way. Say you have:

``````a = [4.1, 6.21, 1.0]
``````

so here’s some code…

``````def array_in_array(scalarlist):
return [(x,) for x in scalarlist]
``````

``````In : a = [4.1, 6.21, 1.0]

In : a
Out: [4.1, 6.21, 1.0]

In : def array_in_array(scalarlist):
....:     return [(x,) for x in scalarlist]
....:

In : b = array_in_array(a)

In : b
Out: [(4.1,), (6.21,), (1.0,)]
``````