Sub topic 1
Reading Your First CSV File
Prerequisites
This chapter assumes basic Python, pandas installation, and familiarity with a DataFrame. A DataFrame is a table-like object with labeled rows and columns.
Load and inspect a CSV
A CSV file stores tabular data as text. Each line usually represents a row, and commas separate values. read_csv loads the file into a DataFrame.
import pandas as pd
df = pd.read_csv("customers.csv")
print(df.head())
print(df.info())head() displays the first five rows. info() reports the row count, column names, non-null values, and inferred data types.
Separators, headers, and the index
Files do not always use commas. Use sep for another separator. If a file has no header row, pass header=None and provide names. An index is the label used to identify rows. Set one while loading with index_col.
from io import StringIO
import pandas as pd
text = "101;Ana\n102;Ben\n"
df = pd.read_csv(
StringIO(text),
sep=";",
header=None,
names=["customer_id", "name"],
index_col="customer_id",
)
print(df)Without header=None, pandas would treat the first data row as column names.
Select columns and rows while reading
Use usecols to load only required columns. Use nrows to limit the number of rows. This reduces work and memory use.
df = pd.read_csv(
"customers.csv",
usecols=["customer_id", "name"],
nrows=1000,
)Set data types at load time
Pandas infers types, but inference can lose information. A postal code such as 02134 should be text, not a number, because numeric conversion removes its leading zero.
df = pd.read_csv(
"customers.csv",
dtype={"postal_code": "string"},
)
print(df.dtypes)Exercise
Which options load the first 20 rows of only the id and amount columns, while keeping id as text?
Show answer
Use pd.read_csv("data.csv", usecols=["id", "amount"], nrows=20, dtype={"id": "string"}).