In this recipe we’ll learn how to add numeric lists into NumPy ndarrays. We’ll look into two cases:
- appending a Python list to the end an existing array (which oculd be either 1d / 2d or more).
- Insert a list into a specific position in the array
Use np.append() to concatenate a list and an array
We’ll use a simple 1d array as an example. Let’s start by importing Numpy.
#Python 3
import numpy as np
first_array = np.array([1265, 1125, 1996, 1527, 1320])
print(first_array)
Here’s our example array:
array([1265, 1125, 1996, 1527, 1320])
first_array.size
#will return 5
Now we’ll define the list that will be appended:
my_list = [2500, 2700, 2900]
Using np.append joins the list at the end of our array:
sec_array = np.append(first_array, my_list)
The size of sec_array will be 8: array([1265, 1125, 1996, 1527, 1320, 2500, 2700, 2900])
Note: The first parameter is the source array, the second is the array that we want to add. Note that both should have the same shape dimension. Optionally you’ll need to specify also also the axis, otherwise the arrays are flattened by default becfore being concatenated.
np.insert to add a list into an array
Consider this code:
third_array = np.insert(first_array, my_list)
This is going to throw the following error:
TypeError: _insert_dispatcher() missing 1 required positional argument: ‘values’
The reason is that unlike np.append(), np.insert expects three parameters: the source array, the position in which we’ll insert the new array and the new array. Optionally you’ll need to specify also also the axis.
third_array = np.insert(first_array, 3, my_list)
print(third_array)
Will result in:
array([1265, 1125, 1996, 2500, 2700, 2900, 1527, 1320])
That’s pretty much it, leave us a comment in case of questions.