Atributos e inspeção de vetores
Explore os atributos ndim, shape, size e dtype e aprenda a remodelar um vetor com reshape().
Atributos e inspeção de vetores é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 2 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.
Why Array Attributes Matter
Before working on an array, you'll want to know its shape, dimensions, and dtype. NumPy hands you these instantly through lightweight attributes.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print('ndim:', a.ndim) # 2
print('shape:', a.shape) # (2, 3)
print('size:', a.size) # 6
print('dtype:', a.dtype) # int64ndim: Number of Dimensions
ndim tells you how many dimensions an array has: a flat list is 1, a list of lists is 2, and ML tensors often go to 3 or 4.
import numpy as np
v = np.array([1, 2, 3])
print(v.ndim) # 1
m = np.zeros((4, 5))
print(m.ndim) # 2
t = np.ones((2, 3, 4))
print(t.ndim) # 3shape: The Dimension Tuple
shape is a tuple with one size per dimension. For a 2-D array, that's (rows, columns) — and you can unpack it to write flexible code.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a.shape) # (2, 3, 4)
n_rows, n_cols = np.zeros((5, 7)).shape
print(n_rows, n_cols) # 5 7size: Total Number of Elements
size gives the total element count — every value in shape multiplied together. Handy for double-checking a reshape didn't lose anything.
import numpy as np
a = np.ones((3, 4, 5))
print(a.size) # 60 (3*4*5)
print(np.prod(a.shape))# 60
# Memory estimate in bytes
print(a.size * a.itemsize, 'bytes') # 480 bytesdtype: Element Data Type
The dtype describes each element's type, and itemsize tells you its byte size. Switching float64 to float32 halves memory and often runs faster.
import numpy as np
a = np.array([1.5, 2.5, 3.5])
print(a.dtype) # float64
print(a.itemsize) # 8 bytes
b = a.astype(np.float32)
print(b.dtype) # float32
print(b.itemsize) # 4 bytesnbytes: Total Memory Usage
nbytes is the array's total memory in bytes — just size times itemsize. Check it before and after downcasting to confirm you actually saved space.
import numpy as np
a = np.ones((1000, 1000), dtype=np.float64)
print(a.nbytes) # 8000000 (8 MB)
b = a.astype(np.float32)
print(b.nbytes) # 4000000 (4 MB)reshape(): Changing Array Shape
reshape gives the array a new shape without copying data, as long as the element count stays the same. Pass -1 and NumPy figures out that dimension for you.
import numpy as np
a = np.arange(12)
print(a.shape) # (12,)
b = a.reshape(3, 4)
print(b.shape) # (3, 4)
c = a.reshape(2, -1) # -1 inferred as 6
print(c.shape) # (2, 6)Flattening with ravel() and flatten()
Both ravel() and flatten() squash an array down to 1-D. The difference: ravel usually shares memory (no copy), while flatten always makes a fresh copy.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
r = m.ravel() # view (usually)
f = m.flatten() # always a copy
print(r) # [1 2 3 4 5 6]
print(f) # [1 2 3 4 5 6]Transposing Arrays
The .T attribute gives you the transpose — rows and columns swapped. It's free (no data copied) and essential for lining up matrices.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3)
print(m.T.shape) # (3, 2)
print(m.T)
# [[1 4]
# [2 5]
# [3 6]]strides: Memory Layout
strides show how many bytes NumPy steps through memory per dimension. This is why transposing is free — it just swaps the stride values.
import numpy as np
a = np.ones((3, 4), dtype=np.float64)
print(a.strides) # (32, 8) — 4 cols x 8 bytes, 1 col x 8 bytes
b = a.T
print(b.strides) # (8, 32) — strides swapped, no data copyChecking Views vs Copies
A view shares memory with the original, so changing one changes both; a copy is independent. Use np.shares_memory(a, b) to check which you have.
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3) # view
print(np.shares_memory(a, b)) # True
c = a.copy()
print(np.shares_memory(a, c)) # FalseQuick Check
Test your understanding of NumPy array attributes from this lesson.
Lesson Recap
Great progress! ndim, shape, and size describe structure, dtype describes the data, and reshape returns a view while flatten always copies. Next: array math.
Perguntas Frequentes
A aula “Atributos e inspeção de vetores” é grátis?
Sim — o texto completo de “Atributos e inspeção de vetores” é 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 “Atributos e inspeção de vetores”?
Explore os atributos ndim, shape, size e dtype e aprenda a remodelar um vetor com reshape(). 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 2 de 4.
Quanto tempo leva a aula “Atributos e inspeção de vetores”?
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