How to Add Elements to NumPy Array (3 Examples)


You can use the following methods to add one or more elements to a NumPy array:

Method 1: Append One Value to End of Array

#append one value to end of array
new_array = np.append(my_array, 15)

Method 2: Append Multiple Values to End of Array

#append multiple values to end of array
new_array = np.append(my_array, [15, 17, 18])

Method 3: Insert One Value at Specific Position in Array

#insert 95 into the index position 2
new_array = np.insert(my_array, 2, 95)

Method 4: Insert Multiple Values at Specific Position in Array

#insert 95 and 99 starting at index position 2 of the NumPy array
new_array = np.insert(my_array, 2, [95, 99]) 

This tutorial explains how to use each method in practice with the following NumPy array:

import numpy as np

#create NumPy array
my_array = np.array([1, 2, 2, 3, 5, 6, 7, 10])

#view NumPy array
my_array

array([ 1,  2,  2,  3,  5,  6,  7, 10])

Example 1: Append One Value to End of Array

The following code shows how to use np.append() to append one value to the end of the NumPy array:

#append one value to end of array
new_array = np.append(my_array, 15)

#view new array
new_array

array([ 1,  2,  2,  3,  5,  6,  7, 10, 15])

The value 15 has been added to the end of the NumPy array.

Example 2: Append Multiple Values to End of Array

The following code shows how to use np.append() to append multiple values to the end of the NumPy array:

#append multiple values to end of array
new_array = np.append(my_array, [15, 17, 18])

#view new array
new_array

array([ 1,  2,  2,  3,  5,  6,  7, 10, 15, 17, 18])

The values 15, 17, and 18 have been added to the end of the NumPy array.

Example 3: Insert One Value at Specific Position in Array

The following code shows how to insert one value into a specific position in the NumPy array:

#insert 95 into the index position 2
new_array = np.insert(my_array, 2, 95)

#view new array
new_array

array([ 1,  2, 95,  2,  3,  5,  6,  7, 10])

The value 95 has been inserted into index position 2 of the NumPy array.

Example 4: Insert Multiple Values at Specific Position in Array

The following code shows how to insert multiple values starting at a specific position in the NumPy array:

#insert 95 and 99 starting at index position 2 of the NumPy array
new_array = np.insert(my_array, 2, [95, 99]) 

#view new array
new_array

array([ 1,  2, 95, 99,  2,  3,  5,  6,  7, 10])

The values 95 and 99 have been inserted starting at index position 2 of the NumPy array.

Additional Resources

The following tutorials explain how to perform other common tasks in NumPy:

How to Filter a NumPy Array
How to Remove NaN Values from NumPy Array
How to Compare Two NumPy Arrays

Leave a Reply

Your email address will not be published.