0Pricing
Pandas & NumPy Academy · Aula

Lendo arquivos CSV

Carregue arquivos CSV com pd.read_csv, controle delimitadores, linhas de cabeçalho e colunas de índice e visualize o resultado.

Lendo arquivos CSV é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 1 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 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 chunk

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

Perguntas Frequentes

A aula “Lendo arquivos CSV” é grátis?

Sim — o texto completo de “Lendo arquivos CSV” é 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 “Lendo arquivos CSV”?

Carregue arquivos CSV com pd.read_csv, controle delimitadores, linhas de cabeçalho e colunas de índice e visualize o resultado. 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 1 de 4.

Quanto tempo leva a aula “Lendo arquivos CSV”?

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

  1. Lendo arquivos CSV
  2. Lendo arquivos Excel e JSON
  3. Escrevendo DataFrames em arquivos
  4. Lendo de URLs e StringIO
← Voltar para Pandas & NumPy Academy