pandas basics · lesson 3 of 9
Parts in this lesson
Apd.read_csv(path, sep=";")a file separated by semicolons
Bna_values=["-"]what counts as missing
Cdf.to_csv(path, index=False)save without the index
Dencoding="cp1252"a file from an old Windows program

Reading and writing files

Last updated

Real data arrives in files, and files are rarely exactly what read_csv expects. In this lesson you'll learn the read_csv options that fix most problems, read JSON, save a clean table without an extra column, and deal with the error that every analyst in the Philippines meets sooner or later: a file whose ñ won't read.

By the end of this lesson you can

  • Read a CSV with the right sep, na_values and parse_dates
  • Read a JSON file into a table
  • Save a table with to_csv(index=False), and say why index=False
  • Fix a UnicodeDecodeError by giving the file’s encoding

The options that matter

A store sends its kilos in a file that uses semicolons, and a dash where it didn't report. Step through what read_csv makes of it with each option:

The same file read four ways. A CSV file is only text. This one uses semicolons between values, and a dash where a store didn’t report.data/kilos.csvdate;store;kilos2024-01-02;Batangas;422024-01-02;Lipa;-2024-01-03;Batangas;382024-01-03;Lipa;33
1 of 5 A CSV file is only text. This one uses semicolons between values, and a dash where a store didn’t report.

Now run it. The file is in the notebook's data folder.

read.ipynb

The options you'll use most:

optionwhat it saysexample
sepwhat's between valuessep=";", or sep="\t" for tabs
na_valuesextra text that means missingna_values=["-", "none"]
parse_datescolumns to read as datesparse_dates=["date"]
dtypea column's type, decided by youdtype={"code": "str"}
encodinghow the text is storedencoding="cp1252", step 4

pandas already treats an empty value, NA, n/a and NaN as missing, and a few more. na_values adds to that list.

dtype matters for codes that look like numbers. A barangay or ZIP code such as 0410 read as a number becomes 410, and the leading zero is gone for good. dtype={"code": "str"} keeps it as text.

JSON, Excel and Parquet

Data from websites often comes as JSON: a list of records, each like a Python dictionary. pd.read_json reads it into a table. Run it.

stores.ipynb

Two other formats you'll meet:

  • Excel: pd.read_excel("sales.xlsx", sheet_name="January") reads one sheet; sheet_name=None reads them all, as a dictionary of tables. It needs the openpyxl package installed.
  • Parquet: df.to_parquet("sales.parquet") and pd.read_parquet(...). A file format built for tables: much smaller than CSV, much faster to read, and it keeps the dtypes, so dates stay dates. It needs pyarrow. Use it for your own in-between files; use CSV when people need to open the file in a spreadsheet.

Neither package runs inside this page, so try those two on your own computer. pip install openpyxl pyarrow in your project's environment, as in lesson 1.4.

Saving a table

Saving is one line. Run the cells, and compare the two files.

save.ipynb

The first file starts date,store,kilos,price, like the one you read. The second starts with a comma: ,date,store,kilos,price, and every row with a number, 0,, 1,, 2,. That's the index, which to_csv saves unless you say index=False.

Read it back and you get a column called Unnamed: 0 that nobody asked for. Save and load a few times and you have Unnamed: 0.1 as well. So: index=False, unless the index holds real information, such as store names.

Remember the rule from lesson 1.5: write to data/clean/, never over the file in data/raw/.

Wrong way: the ñ that won’t read

A list of branches arrives from an old office computer. The first cell makes that file (a real one would just arrive), and shows its first 30 bytes. Run both cells.

branches.ipynb

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1. Look at the bytes in the first cell: Para\xf1aque. The ñ is stored as one byte, f1. That's how Windows-1252 (cp1252), the encoding many older Windows programs use, writes ñ.

pandas reads files as UTF-8 unless you say otherwise. UTF-8 writes ñ as two bytes, c3 b1, and f1 on its own isn't valid UTF-8, so reading stops. (Some programs don't stop: they guess, and give you Parañaque or Para単aque, and you might not notice until the report is printed.)

The fix is to say what the file really is:

branches.ipynb

Parañaque, Las Piñas, Dasmariñas: any Philippine place name with ñ will show this up. When a file won't read, try encoding="cp1252"; when it reads but the letters are wrong, look for à in the text. And when you save, use UTF-8 (the default), so the next person doesn't meet the same problem.

Check what you learned

You read a file and get one column called name|kilos|price. What’s wrong?
Why save with to_csv(path, index=False)?
pd.read_csv("branches.csv") stops with UnicodeDecodeError ... byte 0xf1. What do you try first?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis