Skip to the workspace
Pebellslearn by building
Loading Data  ›  Lesson

Reading CSV Files

CSV 14 minread_csv loads comma-separated text into a DataFrame, but separators, header rows, missing markers and dates often need to be stated, and the result must be checked.

python data analysis / Reading CSV Files

Explore each scene at your own pace.

01 · The rule

The rule

Reading CSV Files

Until now sales was typed by hand. In real life the bookshop's till exports a file called sales.csv every night, and your analysis starts by loading it. CSV is the most common data file in the world, and also the one most likely to be slightly wrong.

The rule

read_csv guesses; tell it what it cannot know, then check what it built.

A CSV file is plain text: one line per row, values separated by commas, usually with a header line of column names.

date,branch,genre,copies,price
2024-03-01,Pune,fiction,3,250
2024-03-01,Delhi,science,5,400
sales = pd.read_csv("sales.csv")

pandas assumes values are split by commas and that the first line is the header, and it guesses each column's type from the values. When the file is unusual, you supply the facts it cannot guess:

pd.read_csv(
    "sales_export.csv",
    sep=";",                     # values split by semicolons, common in Europe
    skiprows=2,                  # two lines of title text before the header
    usecols=["date", "branch", "copies"],   # load only these columns
    parse_dates=["date"],        # turn the date text into real dates
    na_values=["-", "unknown"],      # treat these markers as missing
    encoding="utf-8",
)

Then check what it built, every time:

sales.shape       # did every row arrive?
sales.head()      # do the columns look right?
sales.dtypes      # are numbers numbers?
sales.info()      # types plus non-missing counts per column

Writing goes the other way: sales.to_csv("clean_sales.csv", index=False). Without index=False, the 0, 1, 2… index is saved as an extra unnamed column.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.