Tutorials  /  Python

numpy.append() in Python - Tutorial

Ccentron Redaktion · March 2024 ·5 min read ·Python, Tutorial

The Python numpy.append() function allows for array concatenation and is especially useful when processing data efficiently. It returns a new array while keeping the original array unchanged. This tutorial explains how to use the function and avoid common errors.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

Syntax of numpy.append() Function

Code
numpy.append(arr, values, axis=None)

Parameters:

  1. arr: The source array (NumPy array or array-like object).
  2. values: The values to be appended (array-like object).
  3. axis: The axis along which the values should be appended:
    • None (default): Arrays are flattened and concatenated.
    • 0: Along the first dimension (rows).
    • 1: Along the second dimension (columns).

Return Value:

A new array with the appended values.

Examples of Using numpy.append()

1. Flattening and Concatenating Arrays

import numpy as np

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

arr2 = np.array([[10, 20], [30, 40]])

# Arrays werden abgeflacht und zusammengeführt

arr_flat = np.append(arr1, arr2)

print("Abgeflachtes Array:", arr_flat)

Code

Output:

Abgeflachtes Array: [ 1 2 3 4 10 20 30 40]

2. Concatenating Along an Axis

import numpy as np

# Zusammenführen entlang der Achse 0 (Zeilen)

arr_axis0 = np.append([[1, 2], [3, 4]], [[10, 20], [30, 40]], axis=0)

print("Zusammengeführt entlang Achse 0:\n", arr_axis0)

# Zusammenführen entlang der Achse 1 (Spalten)

arr_axis1 = np.append([[1, 2], [3, 4]], [[10, 20], [30, 40]], axis=1)

print("Zusammengeführt entlang Achse 1:\n", arr_axis1)

Code

Output:

Zusammengeführt entlang Achse 0:

[[ 1 2]

[ 3 4]

[10 20]

[30 40]]

Zusammengeführt entlang Achse 1:

[[ 1 2 10 20]

[ 3 4 30 40]]

Code

3. Concatenating Arrays of Different Shapes

The numpy.append() function works as long as the array dimensions are compatible. If arrays are flattened, they can be concatenated even if their shapes differ.

import numpy as np

# Abflachen und Zusammenführen

arr_flat = np.append([[1, 2]], [[1, 2, 3], [4, 5, 6]])

print("Zusammenführung von Arrays unterschiedlicher Form:\n", arr_flat)

# Zusammenführung entlang der Achse 0

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

print("Zusammengeführt entlang Achse 0:\n", arr_axis0)

Code

Output:

Zusammenführung von Arrays unterschiedlicher Form:

[1 2 1 2 3 4 5 6]

Zusammengeführt entlang Achse 0:

[[1 2]

[3 4]

[5 6]]

Code

4. Common Error with Incompatible Dimensions

If the array dimensions are incompatible, numpy.append() raises a ValueError.

import numpy as np

# Fehler: Unterschiedliche Formen entlang der Achse 0

arr_error = np.append([[1, 2]], [[1, 2, 3]], axis=0)

Error:

ValueError: all the input array dimensions except for the concatenation axis must match exactly

Solution: Ensure that the dimensions match along the specified axis.

Tips for Using numpy.append()

  1. Check Dimensions:

    Use arr.shape to check the dimensions of arrays before appending

    print(arr1.shape) # Gibt die Form des Arrays zurück

  2. Consider Alternatives:

    For appending along specific axes, numpy.concatenate() is often more efficient.

  3. Avoid Large Arrays:

    For very large arrays, predefine the array and assign values directly. This avoids the overhead of creating a new array with each call to numpy.append().

Common Use Cases

  • Data Analysis: Merging datasets.
  • Image Processing: Combining pixel values from multiple images.
  • Machine Learning: Preparing training data.

Conclusion

The numpy.append() function is a versatile way to concatenate arrays in Python. It offers options for flattening arrays and appending along specific axes. To achieve optimal results, ensure that the dimensions of the arrays are compatible and consider using alternatives like numpy.concatenate() for large datasets.

Try the examples above and integrate numpy.append() into your Python projects!

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren