Sub topic 1
Reading your first CSV file
Prerequisites
This chapter assumes you can run Python scripts or notebooks and install packages with pip. It also assumes you know what a DataFrame is and what a CSV file looks like. Install pandas with pip install pandas if you have not already.
What read_csv does
A CSV (comma-separated values) file stores one row per line, with fields separated by commas. The function pandas.read_csv reads that text and returns a DataFrame. With default settings it does four things:
- Splits each line on commas.
- Treats the first line as column names.
- Infers a data type for each column from its values.
- Numbers the rows 0, 1, 2, and so on as the index.
The first argument can be a file path, a URL, or a file-like object, which is any object you can read from, such as an open file.
A first example
The example below uses StringIO to wrap a string so it behaves like a file. That keeps the code self-contained. With a real file you would pass its path, such as pd.read_csv("people.csv").
import pandas as pd
from io import StringIO
text = "id,name,signup\n1,Ana,2024-01-05\n2,Ben,2024-02-11\n"
df = pd.read_csv(StringIO(text))
print(df.head())
df.info()head() shows the first five rows, which is all of them here. info() prints the column names, the data types and the count of non-null values. It prints directly, so you do not wrap it in print.
You should see id as int64, because every value is a whole number. The name column appears as object or str, depending on your pandas version, because it holds text. The signup column also appears as text. pandas does not turn date-like strings into dates unless you ask it to. Later chapters cover that.
How the pieces fit together
The diagram shows the path from file to DataFrame.
Common first errors
Most failures on a first read come from a few causes.
- FileNotFoundError: the path is wrong. Relative paths resolve from the directory where Python runs, not from the script's location. Print
os.getcwd()if you are unsure. - Everything lands in one column: the file uses a different separator, such as a semicolon. The
separgument fixes this. - The first data row is used as column names: the file has no header line. The
header=Noneargument fixes this. - UnicodeDecodeError: the file is not saved as UTF-8. The
encodingargument fixes this.
Later chapters cover each of these in detail.
Exercise
Exercise
You run pd.read_csv(StringIO("id,name\n1,Ana\n2,Ben\n")). How many rows and columns does the DataFrame have, and why is the header line not counted as a row?
Show answer
It has 2 rows and 2 columns. By default read_csv treats the first line as column names, so "id,name" becomes the column labels. Only the two data lines become rows.