Aritmética elemento a elemento
Sume, reste, multiplique y divida arrays elemento a elemento, y comprenda cómo NumPy evita los bucles explícitos de Python.
Aritmética elemento a elemento es una lección gratuita de Pandas & NumPy Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Pandas & NumPy Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Pandas & NumPy Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Problem with Python Loops
Adding lists in pure Python needs a slow loop. NumPy does it in fast C instead — often 10 to 100 times quicker. This trick is called vectorisation. ⚡
# Python list approach -- slow
a = [1, 2, 3, 4]
b = [10, 20, 30, 40]
result = [x + y for x, y in zip(a, b)]
print(result) # [11, 22, 33, 44]
# NumPy approach -- fast
import numpy as np
na, nb = np.array(a), np.array(b)
print(na + nb) # [11 22 33 44]Addition and Subtraction
The + and - operators work element by element on arrays of the same shape, pairing up matching positions in one quick pass.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(a + b) # [11 22 33]
print(a - b) # [ 9 18 27]Multiplication and Division
Use * and / for element-wise multiplication and division — note * is not matrix multiply. Division always gives floats, even from whole numbers.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([2, 4, 5])
print(a * b) # [ 20 80 150]
print(a / b) # [5. 5. 6.]
print(a // b) # [5 5 6]
print(a % b) # [0 0 0]Scalar Arithmetic (Broadcasting Preview)
Add a single number to an array and NumPy applies it to every element. That's broadcasting in its simplest form — great for shifting or scaling data.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a + 10) # [11 12 13 14 15]
print(a * 2) # [ 2 4 6 8 10]
print(a ** 2) # [ 1 4 9 16 25]
print(a / 10) # [0.1 0.2 0.3 0.4 0.5]Exponentiation and Square Root
Use ** to raise every element to a power. For square roots, reach for the np.sqrt ufunc — it's built in C and faster than looping in Python.
import numpy as np
a = np.array([1.0, 4.0, 9.0, 16.0])
print(a ** 0.5) # [1. 2. 3. 4.]
print(np.sqrt(a)) # [1. 2. 3. 4.]
print(a ** 2) # [ 1. 16. 81. 256.]Comparison Operators Return Boolean Arrays
Compare an array with >, ==, or < and you get back a boolean array of True/False values — the foundation for filtering your data.
import numpy as np
a = np.array([3, 7, 2, 9, 1])
print(a > 4) # [False True False True False]
print(a == 2) # [False False True False False]
print(a >= 3) # [ True True False True False]Logical Operators on Boolean Arrays
To combine boolean arrays, use the symbols &, |, and ~ — not the words and/or/not. Wrap each condition in parentheses to avoid precedence surprises.
import numpy as np
a = np.array([3, 7, 2, 9, 1])
mask = (a > 2) & (a < 8)
print(mask) # [ True True False False False]
print(a[mask]) # [3 7]In-Place Operations with +=
Operators like += change an array in place, saving memory by skipping a new copy. Just keep dtypes compatible — you can't add 0.5 to an int array this way.
import numpy as np
a = np.array([1.0, 2.0, 3.0])
a += 10.0
print(a) # [11. 12. 13.]
a *= 2.0
print(a) # [22. 24. 26.]2-D Array Arithmetic
Element-wise math works the same on 2-D arrays: add two matrices of matching shape and each cell sums with its counterpart. No nested loops needed.
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(A + B)
# [[ 6 8]
# [10 12]]
print(A * B) # element-wise, NOT matrix multiply
# [[ 5 12]
# [21 32]]dtype Promotion in Mixed Operations
Mix two dtypes and NumPy promotes both to the safer type, so no info is lost — int plus float gives float. Watch out: this can quietly grow your memory use.
import numpy as np
a = np.array([1, 2, 3], dtype=np.int32)
b = np.array([0.5, 1.5, 2.5], dtype=np.float64)
c = a + b
print(c) # [1.5 3.5 5.5]
print(c.dtype) # float64Absolute Value and Sign
Use np.abs for absolute values and np.sign to get -1, 0, or +1 per element. Both are fast ufuncs, common in loss functions and normalising steps.
import numpy as np
a = np.array([-3, 0, 4, -7, 2])
print(np.abs(a)) # [3 0 4 7 2]
print(np.sign(a)) # [-1 0 1 -1 1]Quick Check
Test your understanding of NumPy element-wise arithmetic from this lesson.
Lesson Recap
You've got it! NumPy does math element-wise with no loops, scalars broadcast across the whole array, and comparisons give boolean arrays. Next: slicing and indexing.
Preguntas frecuentes
¿La lección «Aritmética elemento a elemento» es gratis?
Sí — el texto completo de «Aritmética elemento a elemento» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Pandas & NumPy Academy, actualiza a CoddyKit PRO. El curso de Pandas & NumPy Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Aritmética elemento a elemento»?
Sume, reste, multiplique y divida arrays elemento a elemento, y comprenda cómo NumPy evita los bucles explícitos de Python. Practicas Pandas & NumPy Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Pandas & NumPy Academy?
No se requiere experiencia previa. Pandas & NumPy Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Aritmética elemento a elemento»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Pandas & NumPy Academy?
Sí. Cada lección de Pandas & NumPy Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Creación de arrays de NumPy
- Atributos e inspección de arrays
- Aritmética elemento a elemento
- Indexación y slicing de arrays