Sub topic 1
Reading your first CSV file
Prerequisites
This chapter assumes you can:
- Run Python scripts or notebook cells.
- Install packages with
pip. - Recognize a DataFrame, which is pandas' two-dimensional table of labeled rows and columns.
- Open a CSV file in a text editor or spreadsheet and understand its layout.
You need pandas 2.0 or later. Install it with pip install pandas. Later chapters cover Excel engines, so you don't need them yet.
What read_csv does
A CSV (comma-separated values) file is plain text. Each line is a row, and commas separate the fields. pandas.read_csv parses that text and returns a DataFrame. It does four things by default:
- It splits each line on commas.
- It treats the first line as column names.
- It guesses a data type for each column from its values.
- It gives the rows a numeric index,
0, 1, 2, ....
Everything else in this tutorial changes one of these four defaults.
A minimal example
The following example reads CSV text held in memory. StringIO wraps a string so it behaves like an open file. This makes the example runnable without creating any files.
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()print(df.head()) shows the first rows:
id name signup
0 1 Ana 2024-01-05
1 2 Ben 2024-02-11df.info() prints the column names, non-null counts and dtypes. It writes to the console itself and returns None, so don't wrap it in print. Here id is an integer column. name and signup are text columns, which pandas reports as object in version 2.x. The signup values look like dates, but pandas leaves them as text unless you ask for date parsing. The "Parsing dates" chapter covers that.
What you can pass as the source
The first argument to read_csv is called filepath_or_buffer. It accepts several kinds of source:
| Source | Example | Notes |
|---|---|---|
| Local path | `"data/sales.csv"` | Relative paths resolve against the current working directory, not the script's folder. |
| `pathlib.Path` | `Path("data") / "sales.csv"` | Works the same as a string path. |
| URL | `"https://example.com/data.csv"` | `http`, `https`, `ftp`, `s3` and other schemes are supported. Some, such as `s3`, need extra packages. |
| File-like object | `StringIO(text)`, `open(...)` | Anything with a `read` method. |
| Compressed file | `"data.csv.gz"` | The compression is inferred from the extension (`.gz`, `.zip`, `.bz2`, `.xz`, `.zst`). |
The next example writes a real file and reads it back, so you can run it as is:
from pathlib import Path
import pandas as pd
path = Path("people.csv")
path.write_text("id,name,signup\n1,Ana,2024-01-05\n2,Ben,2024-02-11\n", encoding="utf-8")
df = pd.read_csv(path)
print(df.shape)
print(df.columns.tolist())The output is:
(2, 3)
['id', 'name', 'signup']What the defaults assume
The defaults work when a file matches these assumptions. Most loading problems come from a file that breaks one of them.
- Separator. The delimiter is a comma. A semicolon-separated file loaded with defaults gives you one wide column, with the semicolons still inside the text.
- Header. Row 0 holds column names. If the file has no header, the first data row becomes the column names and you silently lose a row of data.
- Index. The index is a
RangeIndexthat pandas generates. No column becomes the index unless you setindex_col. - Encoding. The file is UTF-8. Other encodings raise
UnicodeDecodeError. - Missing values. Empty fields and a set of strings (
"",NA,N/A,NaN,null, and a few more) becomeNaN. - Types. Pandas picks
int64,float64,boolorobjectfor each column from its values.
The chapters that follow address each of these in turn. For now, the useful habit is to compare what the file looks like with what pandas returned.
How type inference behaves
For each column, pandas tries to convert the values to a number. If every value converts, you get a numeric dtype. If one value fails, the whole column stays as text. A single stray entry such as "n/a?" in a numeric column turns it into object, and sums or averages then fail or concatenate strings.
The following example shows this. The qty column has one bad value:
import pandas as pd
from io import StringIO
text = "item,qty\nbolt,10\nnut,12\nwasher,unknown\n"
df = pd.read_csv(StringIO(text))
print(df.dtypes)
print(df["qty"].tolist())The output is:
item object
qty object
dtype: object
['10', '12', 'unknown']The numbers are still strings, because one value could not be converted. df["qty"].sum() would join the strings instead of adding them. You fix this either by declaring na_values or dtype at load time, or by cleaning afterwards with pd.to_numeric(..., errors="coerce"). Both approaches appear in later chapters.
Integers and missing values
An integer column with a missing value cannot be stored as int64, so pandas converts the whole column to float64. The ids 1, 2, <blank> become 1.0, 2.0, NaN. This is expected behavior. If you need integers with gaps, request a nullable type such as "Int64" with the dtype argument.
Large files and mixed types
For big files, the default C parser reads in internal blocks (low_memory=True). It can infer different types for different blocks of the same column and then warn with DtypeWarning: Columns (3) have mixed types. The warning means that column contains both numbers and text. Treat it as a signal to set that column's dtype explicitly.
Reading without a header
If the file has no header line, tell pandas so. Otherwise it consumes your first data row as column names.
import pandas as pd
from io import StringIO
text = "1,Ana,2024-01-05\n2,Ben,2024-02-11\n"
wrong = pd.read_csv(StringIO(text))
print(wrong.columns.tolist())
right = pd.read_csv(StringIO(text), header=None, names=["id", "name", "signup"])
print(right.shape)The first call yields ['1', 'Ana', '2024-01-05'] as column names and only one data row. The second call keeps both rows. Setting header=None makes pandas number the columns 0, 1, 2, and names replaces those numbers with labels you choose. Chapter 3 covers headers in more detail.
A quick check after every load
Right after loading, run these three checks:
df.shapeconfirms the row and column counts match what you expect from the file.df.dtypesshows whether numeric columns are numeric.df.head()lets you compare the first rows with the raw file.
A wrong shape, such as one column with many rows' worth of text, usually means the wrong separator. Unexpected object columns usually mean stray non-numeric values.
Common errors
| Symptom | Likely cause | First thing to try |
|---|---|---|
| `FileNotFoundError` | Wrong path or working directory | Print `Path.cwd()` and check the path |
| One column containing all fields | File uses `;` or tabs | Pass `sep=";"` or `sep="\t"` |
| `UnicodeDecodeError` | File is not UTF-8 | Pass `encoding="latin-1"` or the correct encoding |
| `ParserError: Error tokenizing data` | A row has more fields than the header | Inspect the line named in the message |
| Numeric column shows as `object` | Non-numeric entries in that column | Find them with `pd.to_numeric(col, errors="coerce")` |
| `EmptyDataError` | The file or buffer has no content | Check that the file is not empty or truncated |
Exercise
A file scores.csv contains the lines ana,90, ben,85 and cy,77, with no header line. You call pd.read_csv("scores.csv"). How many rows does the DataFrame have, what are its column names, and how do you load all three rows with the column names student and score?
Show answer
The DataFrame has 2 rows. The first line ana,90 is used as the column names, so the columns are 'ana' and '90'. The fix is pd.read_csv("scores.csv", header=None, names=["student", "score"]), which returns all 3 rows.
Exercise
A column qty holds the values 10, 12 and unknown. After pd.read_csv, df["qty"].dtype is object. Why, and what does df["qty"].sum() do?
Show answer
Pandas could not convert unknown to a number, so it kept the whole column as text. Calling sum() on string values concatenates them into '1012unknown' instead of adding them.