Pular para o conteúdo principal
Documentos
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy append()

NumPy's `append()` function is used to add elements to the end of an existing array, effectively creating a new array with the additional elements. This operation is useful when you need to expand the contents of an array dynamically.

Usage

The `append()` function is typically used when you want to add more data to an array without altering the original array. It returns a new array with the appended values.

numpy.append(arr, values, axis=None)
  • arr: The input array to which elements are appended.
  • values: The values to be appended to arr. Note that if values have a different data type than arr, the resulting array will have a data type determined by NumPy’s type promotion rules.
  • axis: The axis along which values are appended. If None, values are flattened before use. When axis is specified, values must have the same shape as arr except for the dimension corresponding to the specified axis.

Examples

1. Appending to a 1D Array

import numpy as np

arr = np.array([1, 2, 3])
new_arr = np.append(arr, [4, 5])

In this example, the elements [4, 5] are appended to the array arr, resulting in new_arr being [1, 2, 3, 4, 5].

2. Appending to a 2D Array Without Axis

import numpy as np

arr = np.array([[1, 2], [3, 4]])
new_arr = np.append(arr, [5, 6])

Here, append() flattens arr and then appends [5, 6], resulting in new_arr being [1, 2, 3, 4, 5, 6].

3. Appending to a 2D Array Along an Axis

import numpy as np

arr = np.array([[1, 2], [3, 4]])
new_arr = np.append(arr, [[5, 6]], axis=0)

Here, [[5, 6]] is appended as a new row to arr along axis 0, creating new_arr as [[1, 2], [3, 4], [5, 6]].

Tips and Best Practices

  • Avoid frequent appends. Repeatedly calling append() in a loop can be inefficient; consider using lists for accumulation and converting them to arrays after all data is collected.
  • Use axis carefully. When using the axis parameter, ensure that the dimensions of values match those of arr along the specified axis. For example, if appending along axis 0, values should have the same number of columns as arr.
  • Remember immutability. append() does not modify the original array but creates a new one, so ensure you store the result if needed.
  • Be mindful of performance. Appending to large arrays can be resource-intensive; consider alternative methods for efficiency.