Reading a CSV file
CSV is the most common format in analytics. Under the hood, read_csv is doing several
jobs at once: splitting text into a table, inferring each column's dtype, and deciding what
counts as a row/column index โ which is why it has dozens of optional arguments.
import pandas as pd
df = pd.read_csv("data/sales.csv")
print(df.head())Useful read_csv() options
import pandas as pd
df = pd.read_csv(
"data/sales.csv",
sep=",", # delimiter
encoding="utf-8", # encoding
na_values=["NA", "", "null"],
)
print(df.info())Writing a CSV file
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
df.to_csv("output/cleaned.csv", index=False)Reading Excel files
Excel needs an engine (often openpyxl).
import pandas as pd
df = pd.read_excel("data/sales.xlsx", sheet_name="Sheet1")
print(df.head())Writing Excel
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
df.to_excel("output/cleaned.xlsx", index=False)Reading and writing JSON
Reading JSON
import pandas as pd
df = pd.read_json("data/users.json")
print(df.head())Writing JSON
import pandas as pd
df = pd.DataFrame({"user": ["a", "b"], "score": [10, 20]})
df.to_json("output/users.json", orient="records", indent=2)Visualize it
flowchart LR A["CSV"] --> D["pandas.DataFrame"] B["Excel"] --> D C["JSON"] --> D D --> E["to_csv / to_excel / to_json"]
Practical checklist for file IO
- Always confirm shape:
df.shape - Inspect columns:
df.columns - Preview:
df.head()anddf.sample(5) - Validate types:
df.dtypes - Watch for missing values:
df.isna().sum()
๐งช Try It Yourself
Exercise 1 โ Build a DataFrame from JSON Records
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 2 โ Write to CSV Without the Index
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Exercise 3 โ Treat Custom Strings as Missing Values
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Press Run to see what your code prints.Check your understanding
Why pass index=False to df.to_csv("output/cleaned.csv", index=False)?
Without index=False the row labels are written as an extra unnamed column.
Show answer
A โ To avoid writing the row index as an extra column โ Without index=False the row labels are written as an extra unnamed column.
What does na_values=["NA", "", "null"] do in read_csv?
na_values lists extra strings that should be read as NaN.
Show answer
A โ Treats those strings as missing values (NaN) โ na_values lists extra strings that should be read as NaN.
Which extra is typically needed for read_excel?
Excel files need an engine, and the lesson names openpyxl.
Show answer
A โ An engine such as openpyxl โ Excel files need an engine, and the lesson names openpyxl.
What does orient="records" do in df.to_json?
The records orientation produces a list of objects, one for each row, with indent controlling the layout.
Show answer
A โ Writes a list of row objects, one per row โ The records orientation produces a list of objects, one for each row, with indent controlling the layout.
Next
For faster or larger-than-memory data, continue to Binary Formats and Web APIs (Parquet, pickle, requests).