Aritmética elemento a elemento
Some, subtraia, multiplique e divida vetores elemento a elemento e entenda como NumPy evita laços explícitos em Python.
Aritmética elemento a elemento é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Pandas & NumPy Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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.
Perguntas Frequentes
A aula “Aritmética elemento a elemento” é grátis?
Sim — o texto completo de “Aritmética elemento a elemento” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Pandas & NumPy Academy, atualize para CoddyKit PRO. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
O que vou aprender em “Aritmética elemento a elemento”?
Some, subtraia, multiplique e divida vetores elemento a elemento e entenda como NumPy evita laços explícitos em Python. Você pratica Pandas & NumPy Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Pandas & NumPy Academy?
Nenhuma experiência prévia é necessária. Pandas & NumPy Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Aritmética elemento a elemento”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Pandas & NumPy Academy?
Sim. Cada aula de Pandas & NumPy Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Criando vetores NumPy
- Atributos e inspeção de vetores
- Aritmética elemento a elemento
- Fatiamento e indexação de vetores