Set CSV header handling in pandas read_csv

How the header argument in pandas read_csv decides which lines become column labels, when to use infer, None, names or multi-row headers, and how to avoid silent errors.

The header argument of pandas.read_csv decides which line of a CSV or TSV file, if any, supplies the column labels. Choosing it badly rarely raises an error. Instead, you get a DataFrame that looks plausible but has a header row mixed into the data or a real data row used as labels. This review covers what each setting changes, when to set it explicitly, and how to check the result before relying on it.

Short verdict: when the default is enough and when to set header yourself

The default, header='infer', is suitable for clean files with exactly one header line at the top. Set header explicitly in any of these cases: the file has no header, there is preamble text above the header, the header spans several lines, or you want to replace the file's own column names. The main benefit of being explicit is that the role of every line is decided by you rather than inferred. The tradeoff is that a wrong explicit value is applied without complaint, so an explicit setting is only as reliable as your knowledge of the file. When the file comes from an unfamiliar source, read the first few raw lines as plain text before choosing a header setting.

What the header setting actually changes

The header setting never modifies the file on disk. It only changes how pandas interprets lines in memory. It decides which line or lines become the column Index, which lines before the header are discarded, and which lines are kept as data rows. It can also affect column types indirectly. If a header line is mistakenly read as data, a numeric column will contain text and will usually load as object dtype instead of int or float.

Setting | Column labels come from | Typical use
header='infer' (default) | The first line, unless names is passed, in which case no line is treated as a header | Ordinary files with one header line
header=0 | The first line of data | Being explicit, or combined with names to replace existing labels
header=n | Line n; lines above it are discarded | Files with preamble text above the header
header=None | No line; columns are labeled 0, 1, 2 and so on | Files with no header at all
header=[0, 1] | Several lines, combined into a MultiIndex | Files with stacked, multi-level headers

The interaction between header and names causes the most confusion. Under the default 'infer', passing names switches pandas to header=None behavior. That means the file's original header line is kept as a data row. To discard the file's header and use your own labels in its place, pass header=0 together with names.

import io
import pandas as pd

raw = "id,name,score\n1,Ana,9.5\n2,Ben,7.0\n"

df = pd.read_csv(io.StringIO(raw))
# columns: id, name, score; two data rows

df_none = pd.read_csv(io.StringIO(raw), header=None)
# columns: 0, 1, 2; three rows, the first holding "id", "name", "score"

In the second call, the score column now contains the text "score" alongside numbers, so it loads as text. That dtype change is often the first visible sign that header was set wrong.

Supplying or replacing column names

# Replace the file's header line with your own labels
pd.read_csv(io.StringIO(raw), header=0, names=["user_id", "user", "points"])

# names alone implies header=None: the old header line becomes a data row
pd.read_csv(io.StringIO(raw), names=["user_id", "user", "points"])

Use names alone only for files that genuinely have no header line. The names list must not contain duplicates; current pandas versions raise an error if it does.

When the header is not on the first line

Exported files often start with a title, timestamp or notes. There are two ways to handle this. You can skip those lines with skiprows and let the header be inferred, or you can point header at the right line number. The two count differently. skiprows counts physical lines in the file. According to the pandas documentation, header ignores blank lines (when skip_blank_lines=True, the default) and fully commented lines (when a comment character is set). In other words, header=0 means the first line of data, not necessarily the first line of the file. If a header=n value seems off by one, a blank line above the header is a likely cause.

raw = "Export generated nightly\nid,name\n1,Ana\n"

pd.read_csv(io.StringIO(raw), skiprows=1)
# columns: id, name

Multiple header rows

Passing a list of row numbers builds MultiIndex columns from those lines. The documentation states that any rows between the listed positions are skipped. For example, header=[0, 1, 3] drops row 2. Multi-level headers are useful when a spreadsheet uses grouped headings. However, many downstream steps, such as merges, simple column selection, or writing to another flat format, are easier with single-level labels. A common follow-up is to join the levels into one string per column.

raw = "store,store,sales,sales\nname,code,q1,q2\nNorth,N1,10,12\n"

df = pd.read_csv(io.StringIO(raw), header=[0, 1])
# columns: (store, name), (store, code), (sales, q1), (sales, q2)

df.columns = ["_".join(levels) for levels in df.columns]
# columns: store_name, store_code, sales_q1, sales_q2

Quirks in the header text itself

  • Empty header cells are labeled "Unnamed: N", where N is the column position. This frequently appears when a file was saved with its index.
  • Duplicate header names are made unique by appending suffixes, so a second "price" becomes "price.1". The mangle_dupe_cols option that once controlled this was removed in pandas 2.0.
  • Leading and trailing spaces in header names are kept as part of the label. skipinitialspace=True removes only spaces that follow a delimiter. For a full cleanup, use df.columns = df.columns.str.strip().
  • A UTF-8 byte order mark can end up attached to the first column name, which makes lookups by that name fail. Reading with encoding='utf-8-sig' removes it.
  • For TSV files, pass sep='\t' (or use read_table). All header rules work the same as for comma-separated files.
  • The prefix option, once used to label header-less columns as X0, X1 and so on, was removed in pandas 2.0. Use df.add_prefix('X') after loading instead.

Will the result survive saving and sharing?

Header handling matters again when the DataFrame is written back out. By default, to_csv writes both the column labels and the index. Reading that file back with default settings produces an extra "Unnamed: 0" column. To avoid it, either write with index=False or read with index_col=0. Frames with MultiIndex columns write several header lines, and they are typically read back with header=[0, 1] and index_col=0. Index or level names can add an extra line, so inspect the written file rather than assuming a clean round trip. If the file will be opened by someone else's tool, single-level, plainly spelled column names are the safest choice. Some importers do not understand multi-line headers, and some do not handle a byte order mark.

df.to_csv("out.csv", index=False)
back = pd.read_csv("out.csv")

df.to_csv("out_with_index.csv")
back = pd.read_csv("out_with_index.csv", index_col=0)

Checking the header before committing to a setting

Two quick checks catch most mistakes. First, read only the header with nrows=0 to see what labels pandas would produce, without loading the whole file. Second, print the first few raw lines with repr. This makes hidden characters visible, including byte order marks, stray spaces, tabs and blank lines that affect how header counts.

cols = pd.read_csv("data.csv", nrows=0).columns
print(list(cols))

with open("data.csv", encoding="utf-8") as fh:
    for _ in range(5):
        print(repr(fh.readline()))

Gaps and limits of this overview

No test results, benchmark data or version-specific measurements were supplied for this article. The behavior described here follows the documented pandas 2.x interface. Older releases accepted options, such as prefix and mangle_dupe_cols, that no longer exist. Differences between the C and Python parsing engines in edge cases, such as irregular row lengths around the header, are not covered. Confirm behavior against the pandas version you actually have installed, especially before automating a pipeline that depends on a specific header setting.