Skip to main content
Albero Academy

Loading Data

Read from CSV, Excel and JSON — and write results back out.

Foundations9 min

You'll rarely type data by hand — you read it from a file or database. Pandas has one-line readers for every common format, each returning a DataFrame ready to work with.

Reading files

the read_* family
df = pd.read_csv("students.csv")
df = pd.read_excel("report.xlsx", sheet_name="Sheet1")
df = pd.read_json("data.json")
df = pd.read_sql("SELECT * FROM students", conn)

Useful read_csv options

handle real-world quirks
df = pd.read_csv("students.csv",
parse_dates=["enrolled"], # parse a date column
na_values=["N/A", "-"], # treat these as missing
usecols=["name", "package"], # load only these columns
dtype={"id": str}) # force a column's type

Writing back out

to_* family
df.to_csv("clean.csv", index=False) # index=False avoids an extra column
df.to_excel("out.xlsx", index=False)
df.to_json("out.json", orient="records")

Key takeaways

  1. 01read_csv / read_excel / read_json / read_sql each return a DataFrame in one line.
  2. 02read_csv options handle real data: parse_dates, na_values, usecols, dtype.
  3. 03Write back with to_csv / to_excel / to_json.
  4. 04Use index=False on write unless the index is meaningful.

Finished this chapter?

Mark it complete to track your progress through Pandas.