Inspección básica de DataFrames
Use head(), tail(), info(), describe() y shape para comprender rápidamente el contenido y la estructura de cualquier DataFrame.
Inspección básica de DataFrames es una lección gratuita de Pandas & NumPy Academy en CoddyKit. Esta es la lección 4 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 First Five Steps with Any DataFrame
Whenever you load a new dataset, a systematic inspection sequence saves hours of debugging. The Pandas toolkit for this includes: head() to see the first rows, tail() for the last rows, info() for column types and nulls, describe() for statistics, and shape for dimensions. Running these five checks takes less than a minute and reveals most data quality issues immediately.
import pandas as pd
# Assume df is loaded from a CSV
print(df.shape) # (rows, cols)
df.head() # first 5 rows
df.info() # dtypes + non-null counts
df.describe() # statisticshead() and tail()
df.head(n) returns the first n rows (default 5) as a DataFrame. df.tail(n) returns the last n rows. Together they help you verify that the data was parsed correctly — checking that column names are in the header row, that numeric columns contain numbers, and that date strings were not misinterpreted. They are non-destructive and return new DataFrames.
import pandas as pd
df = pd.DataFrame({'a': range(20), 'b': range(20, 40)})
print(df.head(3))
# a b
# 0 0 20
# 1 1 21
# 2 2 22
print(df.tail(2))
# a b
# 18 18 38
# 19 19 39info(): Types and Non-Null Counts
df.info() prints a concise summary: the index dtype, the number of non-null values per column, each column's dtype, and the total memory usage. Columns with fewer non-null values than the total row count have missing data. Object dtype often means a string column (or a mixed-type column) that may need cleaning before analysis.
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['A', 'B', None],
'score': [80.0, np.nan, 90.0],
'grade': ['A', 'C', 'A']})
df.info()
# Column Non-Null Count Dtype
# name 2 non-null object
# score 2 non-null float64
# grade 3 non-null objectdescribe(): Statistical Summary
df.describe() computes count, mean, std, min, 25th, 50th (median), 75th percentile, and max for all numeric columns. Pass include='all' to also summarise object (string) columns. Pass include='object' to only summarise categoricals. The output is itself a DataFrame, so you can save it or style it for a report.
import pandas as pd
df = pd.DataFrame({'age': [25, 30, 35, 40], 'score': [88, 72, 91, 65]})
print(df.describe().round(1))
# age score
# count 4.0 4.0
# mean 32.5 79.0
# std 6.5 12.0shape, ndim, and size
df.shape is a tuple (nrows, ncols). df.ndim always returns 2 for DataFrames. df.size is the total number of cells. Use len(df) for the number of rows (same as df.shape[0]). These are the simplest sanity checks — confirm the expected row count after loading and after each filtering step.
import pandas as pd
df = pd.DataFrame({'x': range(100), 'y': range(100), 'z': range(100)})
print(df.shape) # (100, 3)
print(len(df)) # 100
print(df.size) # 300
print(df.ndim) # 2dtypes and select_dtypes()
df.dtypes returns a Series mapping each column name to its dtype. df.select_dtypes(include='number') returns a new DataFrame with only numeric columns — useful for computing correlations or applying numeric transformations without accidentally operating on string columns. Pass exclude='object' to drop text columns.
import pandas as pd
df = pd.DataFrame({'a': [1,2], 'b': [1.0,2.0], 'c': ['x','y']})
print(df.dtypes)
# a int64
# b float64
# c object
numeric = df.select_dtypes(include='number')
print(numeric.columns.tolist()) # ['a', 'b']isnull() and Null Counts
df.isnull().sum() gives the count of missing values per column — the quickest way to find which columns need cleaning. Divide by len(df) to get the proportion of missing values. A column with more than 50% missing often needs special treatment: either drop it or apply domain-specific imputation.
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [1, np.nan, 3], 'b': [np.nan, np.nan, 6]})
print(df.isnull().sum())
# a 1
# b 2
print((df.isnull().sum() / len(df)).round(2))
# a 0.33
# b 0.67value_counts() on a DataFrame Column
Calling df['col'].value_counts() lists the frequency of each unique value in that column, sorted by count. Add normalize=True for percentages. Use dropna=False to also count NaN as a category. This is the fastest way to check for category imbalance or unexpected values in a categorical column.
import pandas as pd
df = pd.DataFrame({'status': ['active','inactive','active','active','banned']})
print(df['status'].value_counts())
# active 3
# inactive 1
# banned 1
print(df['status'].value_counts(normalize=True).round(2))columns and index Inspection
df.columns.tolist() gives a plain Python list of column names — useful for programmatic manipulation or for logging. df.index shows the row labels and their type. Check df.index.is_unique to confirm no duplicate row labels exist, which is a prerequisite for many merge operations and time series calculations.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3]}, index=['x', 'y', 'z'])
print(df.columns.tolist()) # ['a']
print(df.index.tolist()) # ['x', 'y', 'z']
print(df.index.is_unique) # Truesample() for Random Inspection
df.sample(n) returns n randomly selected rows without replacement. df.sample(frac=0.1) returns 10% of the rows. Set random_state= for reproducibility. Random sampling is better than head() for spotting issues in the middle of a large dataset that might not appear in the first few rows.
import pandas as pd
df = pd.DataFrame({'x': range(1000), 'y': range(1000)})
print(df.sample(3, random_state=42))
print(df.sample(frac=0.005, random_state=0)) # 0.5% of rowsmemory_usage() for Size Budgeting
df.memory_usage(deep=True) returns the memory used by each column in bytes. deep=True forces accurate measurement of object-dtype columns whose strings live outside the DataFrame buffer. Sum the values to get total memory. Use this before and after dtype downcasting to confirm you have reduced memory consumption.
import pandas as pd
df = pd.DataFrame({'a': range(10000), 'b': [str(i) for i in range(10000)]})
usage = df.memory_usage(deep=True)
print(usage)
print('Total bytes:', usage.sum())Quick Check
Test your understanding of basic DataFrame inspection from this lesson.
Lesson Recap
In this lesson you learned: head() and tail() let you visually inspect the start and end of a DataFrame, info() reveals dtypes and missing value counts in a single call, and describe() provides statistical summaries for numeric columns. Next up we load data from the most common file formats — CSV, Excel, and JSON — into DataFrames.
Preguntas frecuentes
¿La lección «Inspección básica de DataFrames» es gratis?
Sí — el texto completo de «Inspección básica de DataFrames» 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 «Inspección básica de DataFrames»?
Use head(), tail(), info(), describe() y shape para comprender rápidamente el contenido y la estructura de cualquier DataFrame. 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 4 de 4.
¿Cuánto tiempo toma la lección «Inspección básica de DataFrames»?
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 DataFrames
- Selección de columnas y filas
- Añadir y eliminar columnas
- Inspección básica de DataFrames