TExcelTAD
Home › pandas › Pandas Read CSV

Pandas Read CSV

CSV (comma-separated values) is the most common way to exchange tables: a plain text file where each line is a row and commas separate the columns. The first line usually holds the column names. pandas reads it with pd.read_csv().

Reading a CSV

In a real project you pass a file path or a URL:

python
import pandas as pd

df = pd.read_csv("weather.csv")                       # a file next to your script
df = pd.read_csv("data/2024/weather.csv")             # a relative path
df = pd.read_csv("https://example.com/weather.csv")   # a URL works too

The playgrounds on this site cannot open files or reach the network, so we wrap CSV text in io.StringIO. StringIO makes a string behave like an open file, and read_csv accepts it exactly as it would a path:

python · try it yourself
import io
import pandas as pd

csv_text = """station,date,temp_c,rain_mm
Harbor,2024-03-01,7.5,0.0
Harbor,2024-03-02,6.1,4.2
Hilltop,2024-03-01,3.9,1.1
Hilltop,2024-03-02,2.4,6.8
"""
weather = pd.read_csv(io.StringIO(csv_text))
print(weather)
print(weather.dtypes)
   station        date  temp_c  rain_mm
0   Harbor  2024-03-01     7.5      0.0
1   Harbor  2024-03-02     6.1      4.2
2  Hilltop  2024-03-01     3.9      1.1
3  Hilltop  2024-03-02     2.4      6.8
station     object
date        object
temp_c     float64
rain_mm    float64
dtype: object

pandas guessed the types: numbers became float64, while the station names and the dates stayed text (object). Dates are read as plain strings unless you ask for parsing (see below).

Printing big tables

When a DataFrame has more than 60 rows (the default display.max_rows), print() shows only the first and last five with ... in between, plus the size of the table. to_string() forces the full table, and head()/tail() show the start or end:

python · try it yourself
import io
import pandas as pd

lines = ["day,visitors"] + [f"{d},{100 + d * 7}" for d in range(1, 81)]
visits = pd.read_csv(io.StringIO("\n".join(lines)))
print(visits)
print(visits.head(3))
    day  visitors
0     1       107
1     2       114
2     3       121
3     4       128
4     5       135
..  ...       ...
75   76       632
76   77       639
77   78       646
78   79       653
79   80       660

[80 rows x 2 columns]
   day  visitors
0    1       107
1    2       114
2    3       121

Tip: print(df.to_string()) prints every row, which is fine for small data but floods the screen for large files. Prefer head(), tail() and sample().

Useful read_csv parameters

Parameter What it does Example
sep column separator sep=";" or sep="\t"
usecols read only some columns usecols=["date", "temp_c"]
index_col use a column as the index index_col="date"
parse_dates convert columns to datetimes parse_dates=["date"]
dtype force column types dtype={"zip": str}
na_values extra strings meaning "missing" na_values=["-", "n/a"]
nrows read only the first n rows nrows=1000
skiprows skip lines at the top skiprows=2
header which line holds names (None = no header) header=None
decimal decimal mark decimal=","

Many European exports use semicolons and decimal commas. Here a few parameters handle that, plus a placeholder - for a missing value:

python · try it yourself
import io
import pandas as pd

text = """sensor;reading;unit
A-01;12,5;kPa
A-02;-;kPa
A-03;11,75;kPa
"""
df = pd.read_csv(io.StringIO(text), sep=";", decimal=",", na_values=["-"])
print(df)
print(df["reading"].mean())
  sensor  reading unit
0   A-01    12.50  kPa
1   A-02      NaN  kPa
2   A-03    11.75  kPa
12.125

Parsing dates and choosing the index

python · try it yourself
import io
import pandas as pd

csv_text = """date,orders,returns
2024-05-01,31,2
2024-05-02,27,0
2024-05-03,40,5
"""
shop = pd.read_csv(io.StringIO(csv_text), parse_dates=["date"], index_col="date")
print(shop)
print(shop.index.dtype)
print(shop.loc["2024-05-02"])
            orders  returns
date
2024-05-01      31        2
2024-05-02      27        0
2024-05-03      40        5
datetime64[ns]
orders     27
returns     0
Name: 2024-05-02 00:00:00, dtype: int64

With parse_dates, the date column becomes the datetime64 type, and with index_col it becomes the row labels, so you can look rows up by date.

Files without a header

python · try it yourself
import io
import pandas as pd

raw = "17,red\n4,blue\n23,green\n"
df = pd.read_csv(io.StringIO(raw), header=None, names=["id", "color"])
print(df)
   id  color
0  17    red
1   4   blue
2  23  green

header=None tells pandas the first line is data, and names= supplies the column names.

Test yourself

Which parameter reads a semicolon-separated file?

  1. delimiter_char=";"
  2. sep=";"
  3. split=";"
  4. columns=";"

Why do the playgrounds use io.StringIO(...) with read_csv?

  1. read_csv only accepts StringIO
  2. It makes a string behave like a file, because the playground cannot open files
  3. It speeds up parsing
  4. It converts the text to JSON

How do you make pandas convert a date column into real datetimes while reading?

  1. dtype={"date": "date"}
  2. parse_dates=["date"]
  3. dates=True
  4. index_col="date"