Sub topic 3
Handling separators, headers and the index
This chapter assumes you can run pd.read_csv on a well-formed file and know what a DataFrame is. Here you will load files that do not follow the default layout: a different separator, a missing or misplaced header, and a column that should become the index.
Separators
read_csv assumes fields are separated by commas. If a file uses another character, the whole line lands in one column. Pass sep to fix this.
import pandas as pd
from io import StringIO
text = "id;name;score\n1;Ana;90\n2;Ben;85\n"
df = pd.read_csv(StringIO(text), sep=";")
print(df)Common values are ";", "\t" for tab-separated files, and "|". For columns aligned with a variable number of spaces, use the regular expression sep=r"\s+".
Setting sep=None with engine="python" makes pandas guess the separator. It is slower and can guess wrong, so use it only to explore a file, then hard-code the result.
Headers
By default, header=0 means the first line holds the column names. Three situations need other settings.
| Situation | Setting |
|---|---|
| The file has no header row | `header=None`, optionally with `names=[...]` |
| The header is on a later line | `header=N`, where N is the zero-based line number |
| The header is poor and you want your own names | `header=0` with `names=[...]` |
Without a header row, pandas numbers the columns 0, 1, 2. Supply names to label them.
import pandas as pd
from io import StringIO
text = "1,Ana,90\n2,Ben,85\n"
df = pd.read_csv(StringIO(text), header=None, names=["id", "name", "score"])
print(df.columns.tolist())When a file starts with a title or export note, point header at the real header line. Lines above it are discarded.
import pandas as pd
from io import StringIO
text = "Exported 2024-03-01\nid,name\n1,Ana\n2,Ben\n"
df = pd.read_csv(StringIO(text), header=1)
print(df)skiprows=N also drops leading lines. It is useful when you want to skip lines and still have header=0 apply to the first remaining line.
The index
Pandas gives each row a default index of 0, 1, 2, and so on. If one column identifies each row, make it the index while loading with index_col. You can pass a column name or a position.
import pandas as pd
from io import StringIO
text = "id,name,score\n1,Ana,90\n2,Ben,85\n"
df = pd.read_csv(StringIO(text), index_col="id")
print(df.loc[2, "name"])Passing a list, such as index_col=["region", "id"], builds a MultiIndex. Be careful with files that end each line with a trailing delimiter. Pandas may then treat the first column as the index by accident. Use index_col=False to prevent that.
Choosing the options
Always look at the first few lines of the raw file before choosing options. You can print them without pandas:
with open("data.csv", encoding="utf-8") as f:
for _ in range(5):
print(f.readline().rstrip())Exercise
A file begins with the line "Report for March", followed by the header line "sku;qty" and rows such as "A1;4". Which call loads it with sku as the index?
Show answer
pd.readcsv("report.csv", sep=";", header=1, indexcol="sku"). The sep handles the semicolons, header=1 treats the second line as the header and discards the title, and index_col="sku" makes that column the index.