How to Add a New Value to a NumPy Array

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Let's learn how to add a new value to a Numpy array. Adding elements in a NumPy array is not straightforward compared to adding them to standard Python lists.

Adding Values to NumPy Array using np.append()

The np.append() function is used to add new values at the end of an existing NumPy array. This method creates a new array with the appended value(s).

Python
import numpy as np
arr = np.array([1, 2, 3])

# Append a new value
new_arr = np.append(arr, 4)

print(new_arr)  

Output
[1 2 3 4]

Apart from np.append() method, we can use the following methods for adding values to a NumPy array:

Adding Values to NumPy Array using np.insert()

The np.insert() function allows you to insert values at any specific index within the array. You can insert single or multiple values at a chosen position.

Python
import numpy as np
arr = np.array([1, 2, 3])

# Insert a new value at index 1
new_arr = np.insert(arr, 1, 4)
print(new_arr) 

Output
[1 4 2 3]

Adding Values to NumPy Array using np.concatenate()

The np.concatenate() function can be used to add elements by combining two arrays. This is useful when you want to add a larger block of data.

Python
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5])

# Concatenate arrays
new_arr = np.concatenate((arr1, arr2))
print(new_arr)

Output
[1 2 3 4 5]

Adding Values to NumPy Array using np.resize()

The np.resize() function can be used to change the size of an array and fill new elements with a specified value. This method is useful when you need to expand the array to a larger size.

Python
import numpy as np
arr = np.array([1, 2, 3])

# Resize and add a new value
new_arr = np.resize(arr, 5)
print(new_arr)

Output
[1 2 3 1 2]

In this article, we covered four methods for adding new values to a NumPy array: np.append(), np.insert(), np.concatenate(), and np.resize(). Each method has its own specific use case, depending on whether you want to add values at the end, insert at a particular index, or expand the array with new data.


Next Article

Similar Reads