append a value to a numpy array in python

To append a value to a NumPy array in Python, we can use the numpy.append() method.

Here is an example of how to use this method:

main.py
import numpy as np

# create an empty numpy array
my_array = np.array([])

# append a value to the numpy array
my_array = np.append(my_array, 1)

# print the array to verify that the value was appended
print(my_array)
218 chars
11 lines

This will output:

main.py
[1.]
5 chars
2 lines

Note that numpy.append() returns a new array with the appended values and the original array is not modified. Therefore, we need to assign the returned value to a variable to keep the appended value.

We can also append multiple values at once by passing a sequence of values to numpy.append(), for example:

main.py
import numpy as np

# create an empty numpy array
my_array = np.array([])

# append multiple values to the numpy array
my_array = np.append(my_array, [1, 2, 3])

# print the array to verify that the values were appended
print(my_array)
236 chars
11 lines

This will output:

main.py
[1. 2. 3.]
11 chars
2 lines

related categories

gistlibby LogSnag