read_csv() (Pandas)

pd.read_csv() reads a comma-separated values file (or any delimited text) into a DataFrame. It is the most common way to load tabular data into pandas from disk or a URL.

Pandas

read_csv is fast and extremely configurable. Beyond the file path it accepts dozens of arguments: sep to change the delimiter, header to pick the header row, names to supply column names, usecols to read only some columns, and dtype to force types so pandas doesn't have to guess.

Two arguments save a lot of grief: parse_dates turns text date columns into real datetime64 values, and na_values tells pandas which strings (like 'NA' or '-') should be treated as missing. For files too big to fit in memory, chunksize streams the file in pieces.

It accepts file-like objects too, so you can read from a StringIO buffer or a remote URL exactly as you would a local path.

Syntax

pd.read_csv(filepath, sep=',', header='infer', index_col=None, dtype=None, parse_dates=None)

Examples

Python — StringIO lets us read CSV text without a file.

import pandas as pd
from io import StringIO
csv = "a,b\n1,3\n2,4\n"
df = pd.read_csv(StringIO(csv))
print(df)

Output:

   a  b
0  1  3
1  2  4

Learn it in a lesson

See also

Back to the Dictionary