Lectura de archivos CSV
Cargue archivos CSV con pd.read_csv, controle los delimitadores, las filas de encabezado y las columnas de índice, y previsualice el resultado.
Lectura de archivos CSV es una lección gratuita de Pandas & NumPy Academy en CoddyKit. Esta es la lección 1 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 CSV Is the Universal Format
CSV (Comma-Separated Values) is the most widely used format for exchanging tabular data. It is human-readable, supported by every database, spreadsheet, and analytics tool, and requires no schema definition. pd.read_csv() is the most frequently called Pandas function in data analysis because virtually every public dataset, API export, or database dump is available in CSV.
import pandas as pd
# Read a CSV file from disk
df = pd.read_csv('data/sales.csv')
print(df.shape)
print(df.head())Basic read_csv() Call
The only required argument is the file path (string or Path object). By default Pandas assumes the first row is the header (column names), the delimiter is a comma, and values are inferred to appropriate dtypes. The resulting DataFrame has a default integer RangeIndex. Always call df.info() immediately after loading to spot type inference issues.
import pandas as pd
df = pd.read_csv('products.csv')
# Equivalent with explicit defaults:
df = pd.read_csv('products.csv',
sep=',',
header=0,
index_col=None)Controlling the Delimiter
Use the sep= parameter to specify a non-comma delimiter. Tab-separated files (TSV) use sep='\t'. Some European exports use semicolons as separators (sep=';') because commas are used as decimal separators. Pass sep=None, engine='python' to let Pandas auto-detect the separator from the file content.
import pandas as pd
# Tab-separated file
df_tsv = pd.read_csv('data.tsv', sep='\t')
# Semicolon-separated (common in Europe)
df_semi = pd.read_csv('data.csv', sep=';')
# Auto-detect separator
df_auto = pd.read_csv('data.txt', sep=None, engine='python')Header and skiprows
If a CSV has no header row, set header=None and Pandas will assign integer column names (0, 1, 2, ...). Provide custom names with names=['a', 'b', 'c']. Use skiprows=n to skip the first n rows (for metadata or comments at the top of the file). skiprows also accepts a list of specific row numbers to skip.
import pandas as pd
# CSV with no header
df = pd.read_csv('noheader.csv', header=None,
names=['id', 'value', 'category'])
# Skip first 3 rows (e.g., metadata or comments)
df = pd.read_csv('report.csv', skiprows=3)Setting the Index Column
index_col= specifies which column to use as the row index. Pass a column name or integer position. Setting a meaningful index (e.g., a date column or a unique ID) enables fast label-based access with .loc and is required before time-series operations. Pass a list for a MultiIndex.
import pandas as pd
# Use 'date' column as row index
df = pd.read_csv('timeseries.csv', index_col='date', parse_dates=True)
print(df.index.dtype) # datetime64[ns]
# Equivalent with column position
df2 = pd.read_csv('timeseries.csv', index_col=0, parse_dates=True)Parsing Dates on Load
parse_dates=True tells Pandas to try converting the index to datetime. Pass a list of column names to parse_dates=['col1', 'col2'] to parse specific non-index columns as dates. Pandas will try common formats automatically; for unusual formats use date_format=. Parsing dates at load time avoids repeated pd.to_datetime() calls later.
import pandas as pd
# Parse 'order_date' column as datetime
df = pd.read_csv('orders.csv',
parse_dates=['order_date'])
print(df['order_date'].dtype) # datetime64[ns]Selecting Columns with usecols
usecols=['col1', 'col2'] loads only the specified columns, ignoring all others. This is critical for large CSV files — there is no need to read a 200-column file if you only need 5 columns. It reduces both I/O time and memory usage significantly. Pass a callable to select columns by a name pattern.
import pandas as pd
# Load only 3 of potentially many columns
df = pd.read_csv('big_file.csv',
usecols=['user_id', 'event', 'timestamp'])
print(df.columns.tolist()) # ['user_id', 'event', 'timestamp']Controlling dtypes on Load
Pandas infers dtypes, but inference can be wrong — an ID column of all-numeric strings becomes int64, or a price column with missing values becomes float64 unexpectedly. Use dtype={'col': str} to enforce types. This is also more efficient: pre-specifying dtypes skips the inference pass and can speed up loading large files by 20-30%.
import pandas as pd
df = pd.read_csv('orders.csv', dtype={
'order_id': str, # keep as string (not int)
'price': float,
'quantity': 'int32' # use smaller int
})Handling Missing Values on Load
By default Pandas recognises many missing value representations: empty cells, 'NA', 'NaN', 'N/A', 'null', etc. Use na_values=['?', '-', 'missing'] to add custom tokens. Use keep_default_na=False to disable the built-in list and only treat the values you specify as missing. This prevents accidentally treating legitimate string values like 'NA' (an acronym) as NaN.
import pandas as pd
df = pd.read_csv('survey.csv',
na_values=['?', '', 'N/A', 'none'])
print(df.isnull().sum())nrows and chunksize for Large Files
nrows=100 loads only the first 100 rows — perfect for a quick schema check on a massive file. chunksize=10000 returns a TextFileReader iterator that yields DataFrames of 10000 rows each, enabling chunked processing of files that do not fit in RAM. Chunked reading is covered in depth in the advanced performance lesson.
import pandas as pd
# Quick peek at a large file
header_df = pd.read_csv('huge.csv', nrows=5)
print(header_df.dtypes)
# Chunked reading
for chunk in pd.read_csv('huge.csv', chunksize=50000):
print(chunk.shape) # process each chunkCommon Gotchas with read_csv
Watch out for these frequent issues: encoding errors (use encoding='utf-8' or 'latin-1'), leading spaces in column names (use skipinitialspace=True), thousands separators in numbers (use thousands=','), and decimal commas in European numbers (use decimal=',' and sep=';'). Each of these silently turns numeric columns into objects if ignored.
import pandas as pd
# European format: semicolon sep, comma decimal, UTF-8
df = pd.read_csv('euro_data.csv',
sep=';',
decimal=',',
thousands='.',
encoding='utf-8',
skipinitialspace=True)Quick Check
Test your understanding of reading CSV files with Pandas from this lesson.
Lesson Recap
In this lesson you learned: pd.read_csv() is the primary function for loading tabular data with many configuration parameters, sep, header, index_col, and parse_dates control how the file is interpreted, and usecols and dtype improve performance and type safety for large files. Next up we read Excel and JSON files, which have their own format-specific parameters.
Preguntas frecuentes
¿La lección «Lectura de archivos CSV» es gratis?
Sí — el texto completo de «Lectura de archivos CSV» 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 «Lectura de archivos CSV»?
Cargue archivos CSV con pd.read_csv, controle los delimitadores, las filas de encabezado y las columnas de índice, y previsualice el resultado. 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 1 de 4.
¿Cuánto tiempo toma la lección «Lectura de archivos CSV»?
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
- Lectura de archivos CSV
- Lectura de archivos Excel y JSON
- Escritura de DataFrames en archivos
- Lectura desde URL y StringIO