Python:NumPy .append()

Anonymous contributor's avatar
Anonymous contributor
Published May 25, 2022Updated Oct 18, 2024
Contribute to Docs

The .append() function adds values to the end of an array and returns a ndarray with the values appended.

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

numpy.append(array, values, axis)

Where array is the array being appended to. The values parameter is another array specifying the values to add to array. If axis is specified, values must be the same shape as array without that axis. If axis is not specified, values can be any shape, and both array and values will be flattened before the values are appended. The axis value specifies the axis along which values are appended.

Example

The example below creates two ndarrays and appends one to the other.

import numpy as np
nd1 = np.array([[1,2,3],[4,5,6]])
nd2 = np.array([[7,8,9]])
print(nd1)
print(nd2)
print(np.append(nd1,nd2,0))

This produces the following output:

[[1 2 3]
[4 5 6]]
[[7 8 9]]
[[1 2 3]
[4 5 6]
[7 8 9]]

Codebyte Example

The following example creates two arrays and demonstrates appending them using .append(), both without specifying an axis (resulting in a 1D array) and along specified axes (rows and columns):

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python:NumPy on Codecademy

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours