0Pricing
Pandas & NumPy Academy · Lección

Atributos e inspección de arrays

Explore los atributos ndim, shape, size y dtype, y aprenda a cambiar la forma de un array con reshape().

Atributos e inspección de arrays es una lección gratuita de Pandas & NumPy Academy en CoddyKit. Esta es la lección 2 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.

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)  # int64

ndim: 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)   # 3

shape: 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 7

size: 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 bytes

dtype: 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 bytes

nbytes: 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 copy

Checking 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))  # False

Quick 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.

Preguntas frecuentes

¿La lección «Atributos e inspección de arrays» es gratis?

Sí — el texto completo de «Atributos e inspección de arrays» 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 «Atributos e inspección de arrays»?

Explore los atributos ndim, shape, size y dtype, y aprenda a cambiar la forma de un array con reshape(). 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 2 de 4.

¿Cuánto tiempo toma la lección «Atributos e inspección de arrays»?

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

  1. Creación de arrays de NumPy
  2. Atributos e inspección de arrays
  3. Aritmética elemento a elemento
  4. Indexación y slicing de arrays
← Volver a Pandas & NumPy Academy