Skip to content

NumPy array append in Python | Example code

  • by

Use The NumPy append() method to appends values along the mentioned axis at the end of the array.

numpy.append(array, values, axis = None)

axis (int, optional)

The axis along which values are appended. If the axis is not given, both arr and values are flattened before use.

NumPy Array append Example

Flattened append array code.

import numpy as np

arr1 = np.array([1,2])
arr2 = np.array([1,2])

arr_new = np.append(arr1,arr2)

print(arr_new)

Output:

NumPy array append in Python

Appending the arrays with axis = 0 and 1

When the axis is specified, values must have the correct shape.

import numpy as np

arr1 = np.array([[1, 2, 3], [1, 2, 3]])
arr2 = np.array([[4, 5, 6], [4, 5, 6]])

print("axis = 0")
arr_new = np.append(arr1, arr2, axis=0)
print(arr_new)

print("axis = 1")
arr_new = np.append(arr1, arr2, axis=1)
print(arr_new)

Output:

axis 0 and 1 NumPy array append in Python

Do comment if you have any doubts and suggestions on this NumPy array topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *