Sub topic 3
Handling separators, headers and the index
This chapter assumes you can run Python scripts or notebooks, have pandas installed, and know what a DataFrame is. You should also have seen read_csv load a simple file. Here you will learn how to load files that do not follow the default layout: a comma as separator, column names in the first row, and a plain row number as the index.
What read_csv assumes by default
Without extra arguments, read_csv makes three assumptions:
- Fields are separated by a comma.
- The first line holds the column names.
- Rows are labeled
0, 1, 2, ...and no column becomes the index.
Real files often break one or more of these. The arguments sep, header, names, skiprows and index_col let you describe the actual layout.
Choosing the separator
The sep argument sets the character that separates fields. Semicolons are common in files exported from software set to a European locale, because the comma is used there as a decimal mark. Tabs are common in .tsv files and in database dumps.
import pandas as pd
from io import StringIO
text = "id;name;city\n1;Ana;Lisbon\n2;Ben;Oslo\n"
wrong = pd.read_csv(StringIO(text))
print(wrong.shape)
right = pd.read_csv(StringIO(text), sep=";")
print(right.shape)
print(right)The first call finds no commas, so it reads each line as a single column and the shape is (2, 1). The second call gives (2, 3). A DataFrame with one wide column holding text such as 1;Ana;Lisbon is the usual sign of a wrong separator.
Some common values:
| File type | `sep` value | Column | Column |
|---|---|---|---|
| Comma-separated | `","` (default) | ||
| Semicolon-separated | `";"` | ||
| Tab-separated | `"\t"` | ||
| Pipe-separated | `"\ | "` or `" | "` |
| Runs of spaces | `r"\s+"` |
Two details matter here. First, a separator longer than one character, other than "\s+", is treated as a regular expression, and pandas switches to the slower Python parser. Second, read_csv(..., sep="\t") is the same as read_table(...), whose default is a tab.
If you do not know the separator, pass sep=None with engine="python". pandas then uses Python's csv.Sniffer to guess. This is handy for exploring, but it can guess wrong on small files, so set sep explicitly in code you keep.
import pandas as pd
from io import StringIO
text = "id|name\n1|Ana\n2|Ben\n"
df = pd.read_csv(StringIO(text), sep=None, engine="python")
print(df.columns.tolist())Headers and column names
The header argument says which line holds the column names. Its default, "infer", behaves like header=0 when you do not pass names. There are three common situations.
The file has no header row
Pass header=None so the first line is treated as data. Columns are then numbered 0, 1, 2, .... Add names to give them real labels.
import pandas as pd
from io import StringIO
text = "1,Ana,2024-01-05\n2,Ben,2024-02-11\n"
df = pd.read_csv(
StringIO(text),
header=None,
names=["id", "name", "signup"],
)
print(df)If you pass names and forget header=None on a file that has no header, the first data row is read as a header and then replaced by your names. You lose that row without any error.
The header is not on the first line
Many exports start with a title or a note. Use skiprows to drop lines before the header, or header=N to say the header is on line N (counting from 0, after skipped blank lines).
import pandas as pd
from io import StringIO
text = "Report generated 2024-03-01\n\nid,name\n1,Ana\n2,Ben\n"
df = pd.read_csv(StringIO(text), skiprows=2)
print(df)skiprows=2 removes the first two physical lines, so the header is id,name. skiprows also accepts a list of line numbers, such as [0, 2], or a function that returns True for lines to skip.
Replacing the existing header
To rename columns while still discarding the file's own header, pass both names and header=0.
import pandas as pd
from io import StringIO
text = "ID,Full Name\n1,Ana\n2,Ben\n"
df = pd.read_csv(StringIO(text), header=0, names=["id", "name"])
print(df.columns.tolist())Here header=0 means "line 0 is a header, so skip it", and names supplies the labels that replace it.
Renaming later with df.rename(columns=...) is often better when you only want to change a few names. Use names when you want to replace all of them at the point of loading.
Prefixes and duplicates
If two columns share a name, pandas renames the second one by appending .1, the third .2, and so on. It does this silently, so check df.columns when a file has repeated headings. Passing duplicate labels in names raises a ValueError.
Choosing the index
By default pandas creates a RangeIndex. The index_col argument makes one or more columns the index instead. You can give a column name or a position.
import pandas as pd
from io import StringIO
text = "id,name,city\n1,Ana,Lisbon\n2,Ben,Oslo\n"
df = pd.read_csv(StringIO(text), index_col="id")
print(df)
print(df.loc[2, "name"])The id column moves out of the data and becomes the row labels, so df.loc[2, "name"] returns "Ben". Pass a list, such as index_col=["country", "year"], to get a MultiIndex.
Files written with the index included
When you call df.to_csv("out.csv") without index=False, pandas writes the index as an unnamed first column. Reading that file back gives an extra column called Unnamed: 0.
import pandas as pd
from io import StringIO
text = ",name\n0,Ana\n1,Ben\n"
df = pd.read_csv(StringIO(text))
print(df.columns.tolist())
df = pd.read_csv(StringIO(text), index_col=0)
print(df.columns.tolist())The first call prints ['Unnamed: 0', 'name']. The second prints ['name']. The better fix is on the writing side: use to_csv(path, index=False) unless the index carries information.
Trailing delimiters
Some files end every data line with a delimiter, so each row has one more field than the header. pandas then uses the first column as the index without being asked. This is a known surprise. Pass index_col=False to stop it and force a plain RangeIndex.
import pandas as pd
from io import StringIO
text = "a,b\n1,2,\n3,4,\n"
print(pd.read_csv(StringIO(text)))
print(pd.read_csv(StringIO(text), index_col=False))The first call treats the first column as the index and shifts the values, so a appears to hold the values of b. The second call keeps the columns aligned and drops the extra empty field.
Putting it together
The next example combines separator, skipped lines, custom names and an index in one call.
import pandas as pd
from io import StringIO
text = (
"Exported from ShopSystem\n"
"\n"
"1;Ana;Lisbon\n"
"2;Ben;Oslo\n"
)
df = pd.read_csv(
StringIO(text),
sep=";",
skiprows=2,
header=None,
names=["id", "name", "city"],
index_col="id",
)
print(df)Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| One column containing `a;b;c` text | Wrong `sep` | Set `sep=";"` or the right character |
| `ParserError: Error tokenizing data` | Rows with a different number of fields, or the wrong `sep` | Check `sep`, then see the chapter on bad lines |
| First data row missing | `names` passed without `header=None` | Add `header=None` |
| Column `Unnamed: 0` | File was saved with its index | Use `index_col=0` or write with `index=False` |
| Values shifted one column left | Trailing delimiter on each line | Use `index_col=False` |
| Column names like `price.1` | Duplicate headings in the file | Rename columns after loading |
Exercises
Exercise
A file starts with the line "Quarterly figures", then a blank line, then the header "region;sales", then data rows. Write the read_csv call that loads it with region as the index.
Show answer
pd.readcsv(path, sep=";", skiprows=2, indexcol="region"). The semicolon needs sep=";", skiprows=2 drops the title and the blank line so the header is the first line read, and index_col="region" makes that column the index.
Exercise
You load a file with names=["id", "name"] and find that the first customer is missing. The file has no header row. What went wrong and how do you fix it?
Show answer
Without header=None, pandas treats the first line as a header and replaces it with names, so that row is lost. Add header=None to the call so the first line is read as data.
Exercise
Reading a file you saved earlier gives a column called "Unnamed: 0". Give one fix on the reading side and one on the writing side.
Show answer
On the reading side, pass indexcol=0 to readcsv. On the writing side, call df.to_csv(path, index=False) so the index is not written.