Universelle Funktionen (ufuncs)
Wenden Sie integrierte elementweise Funktionen wie np.sqrt, np.abs, np.exp und np.log auf Arrays an, ohne Schleifen zu schreiben.
Universelle Funktionen (ufuncs) ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
What Are ufuncs?
Universal functions (ufuncs) run a math operation on every element of an array at once, in fast compiled C — far quicker than a Python loop. ⚡
import numpy as np
a = np.array([1.0, 4.0, 9.0, 16.0])
print(np.sqrt(a)) # [1. 2. 3. 4.]
# Equivalent Python loop would be hundreds of times slowerMath ufuncs: sqrt, exp, log
All your favourite math functions are ufuncs: np.sqrt, np.exp, np.log, and more. They apply to whole arrays at once and handle edge cases gracefully.
import numpy as np
a = np.array([0.0, 1.0, 2.0, 3.0])
print(np.exp(a)) # [1. 2.718 7.389 20.086]
print(np.log(np.exp(a))) # [0. 1. 2. 3.]
print(np.log2(np.array([1, 2, 4, 8]))) # [0. 1. 2. 3.]Trigonometric ufuncs
NumPy's trig ufuncs like np.sin and np.cos expect angles in radians. Use np.deg2rad to convert degrees first.
import numpy as np
angles = np.array([0, 30, 60, 90])
rad = np.deg2rad(angles)
print(np.sin(rad).round(4)) # [0. 0.5 0.866 1. ]
print(np.cos(rad).round(4)) # [1. 0.866 0.5 0. ]np.abs, np.floor, np.ceil, np.round
For rounding, reach for np.floor (down), np.ceil (up), and np.round (nearest). They clean up float values across the whole array in one go.
import numpy as np
a = np.array([-2.7, 0.4, 1.5, 3.9])
print(np.abs(a)) # [2.7 0.4 1.5 3.9]
print(np.floor(a)) # [-3. 0. 1. 3.]
print(np.ceil(a)) # [-2. 1. 2. 4.]
print(np.round(a)) # [-3. 0. 2. 4.]np.maximum and np.minimum
np.maximum(a, b) takes the larger value at each position from two arrays — different from np.max, which returns one number. np.maximum(a, 0) is ReLU!
import numpy as np
a = np.array([-3, 1, 5, -2, 4])
b = np.array([0, 0, 3, 3, 3])
print(np.maximum(a, b)) # [0 1 5 3 4]
print(np.minimum(a, b)) # [-3 0 3 -2 3]
# ReLU
print(np.maximum(a, 0)) # [0 1 5 0 4]np.clip for Bounding Values
np.clip keeps every element inside a range: anything too low jumps up to the minimum, anything too high drops to the maximum. Great for bounding values.
import numpy as np
a = np.array([0.1, 0.5, -0.2, 1.3, 0.9])
clipped = np.clip(a, 0.0, 1.0)
print(clipped) # [0.1 0.5 0. 1. 0.9]ufuncs on Multi-Dimensional Arrays
ufuncs work on arrays of any shape. The math hits each element on its own, and the result keeps the same shape — no reshaping required.
import numpy as np
m = np.array([[1.0, 4.0], [9.0, 16.0]])
print(np.sqrt(m))
# [[1. 2.]
# [3. 4.]]out Parameter for Memory Efficiency
Every ufunc takes an out= argument to write results into an array you already have. That skips making a new array — handy in tight, memory-sensitive loops.
import numpy as np
a = np.array([1.0, 4.0, 9.0])
result = np.empty(3)
np.sqrt(a, out=result) # write directly into result
print(result) # [1. 2. 3.]np.add.reduce and .accumulate
Each ufunc has a .reduce() method that combines all elements (np.add.reduce is just sum) and .accumulate() for running totals.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(np.add.reduce(a)) # 15
print(np.add.accumulate(a)) # [ 1 3 6 10 15]
print(np.multiply.reduce(a)) # 120np.frompyfunc for Custom ufuncs
np.frompyfunc turns any Python function into a ufunc you can apply to arrays. It's slower than built-ins, so save it for quick prototyping.
import numpy as np
def clamp_positive(x):
return x if x > 0 else 0.0
vfunc = np.frompyfunc(clamp_positive, 1, 1)
a = np.array([-2, 3, -1, 5])
print(vfunc(a)) # [0.0 3 0.0 5] (object dtype)Comparing ufuncs to Python Loops
The speed gap is huge: on a million elements, a ufunc can be around 200 times faster than a Python loop. In number work, always reach for ufuncs first. 🚀
import numpy as np
import time
a = np.random.rand(1_000_000)
start = time.perf_counter()
np.sqrt(a)
print('ufunc:', round(time.perf_counter() - start, 4), 's')
start = time.perf_counter()
[x ** 0.5 for x in a]
print('loop:', round(time.perf_counter() - start, 4), 's')Quick Check
Test your understanding of NumPy ufuncs from this lesson.
Lesson Recap
Nice work! ufuncs do element-wise math in fast C, cover sqrt, exp, log, and trig, and the out= argument saves memory. Next up: aggregation functions.
Häufig gestellte Fragen
Ist die Lektion „Universelle Funktionen (ufuncs)“ kostenlos?
Ja — der vollständige Text von „Universelle Funktionen (ufuncs)“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Universelle Funktionen (ufuncs)“?
Wenden Sie integrierte elementweise Funktionen wie np.sqrt, np.abs, np.exp und np.log auf Arrays an, ohne Schleifen zu schreiben. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?
Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „Universelle Funktionen (ufuncs)“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?
Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Universelle Funktionen (ufuncs)
- Aggregationsfunktionen
- Broadcasting-Regeln
- Boolesche Maskierung und Fancy Indexing