Day 11: Read CSV, Excel, JSON & Explore
✅ Today you will learn
- read_csv options that save hours
- Read and write Excel sheets
- Read JSON from APIs (json_normalize)
- A 5-minute checklist for any new dataset
- Save cleaned results to CSV / Excel
🏢 In the real world
Your manager mails a 40 MB Excel file at 10 a.m. and asks “What’s in it?” by 11. A repeatable read-and-explore routine lets you answer with confidence – rows, columns, types, missing values, ranges and the first surprises.
read_csv – the most used function
import pandas as pd
sales = pd.read_csv("sales_data.csv")
print(sales.shape)
print(sales.head(3))| Option | What it does | Example |
|---|---|---|
| usecols | Read only some columns (less memory) | usecols=["city", "unit_price"] |
| nrows | Read the first n rows (quick peek) | nrows=1000 |
| parse_dates | Convert date text to real dates | parse_dates=["order_date"] |
| dtype | Force a type, e.g. keep IDs as text | dtype={"pincode": str} |
| sep | Other separators | sep=";" or sep="\t" |
| na_values | Extra words that mean missing | na_values=["NA", "-", "?"] |
| encoding | Files from Excel/Windows | encoding="latin-1" |
import pandas as pd
small = pd.read_csv("sales_data.csv", usecols=["order_date", "city", "category", "unit_price"],
parse_dates=["order_date"], nrows=5)
print(small)
print(small.dtypes)import pandas as pd
from io import StringIO
raw = """id;city;pincode;amount
1;Pune;411001;450
2;Agra;-;?
3;Delhi;110001;1299"""
df = pd.read_csv(StringIO(raw), sep=";", dtype={"pincode": str}, na_values=["-", "?"])
print(df)
print(df.dtypes)Pincodes, phone numbers and IDs like 012345 lose their leading zero if read as numbers. Use dtype={"pincode": str}.
Excel files
import pandas as pd
sales = pd.read_csv("sales_data.csv")
with pd.ExcelWriter("report.xlsx") as xl: # needs: pip install openpyxl
sales[sales["region"] == "North"].to_excel(xl, sheet_name="North", index=False)
sales[sales["region"] == "South"].to_excel(xl, sheet_name="South", index=False)
sheets = pd.read_excel("report.xlsx", sheet_name=None) # all sheets -> dict
for name, df in sheets.items():
print(name, df.shape)
north = pd.read_excel("report.xlsx", sheet_name="North", usecols="A:D", nrows=3)
print(north)JSON and APIs
import pandas as pd
api_response = [
{"id": 1, "customer": {"name": "Riya", "city": "Pune"}, "items": 3, "total": 1450},
{"id": 2, "customer": {"name": "Om", "city": "Delhi"}, "items": 1, "total": 15999},
]
flat = pd.json_normalize(api_response) # nested keys -> columns
print(flat)
flat.to_json("orders.json", orient="records", indent=2)
print(pd.read_json("orders.json").shape)url = "https://example.com/data/sales.csv" # any public CSV link df = pd.read_csv(url) # APIs: import requests; data = requests.get(api_url).json(); pd.json_normalize(data)
The 5-minute exploration checklist
- 1
df.shape– how big? - 2
df.head()/df.sample(5)– what does a row look like? - 3
df.info()– column types and missing counts - 4
df.describe()– ranges of numbers; spot impossible values - 5
df.isna().sum()anddf.nunique()– gaps and categories - 6
df["col"].value_counts()– the big categories
import pandas as pd
df = pd.read_csv("telecom_churn.csv")
print("Shape:", df.shape)
print(df.sample(3, random_state=1))
df.info()import pandas as pd
df = pd.read_csv("telecom_churn.csv")
print(df.describe().round(1))
print("\nMissing values:\n", df.isna().sum()[df.isna().sum() > 0])
print("\nUnique values per column:\n", df.nunique())import pandas as pd
df = pd.read_csv("telecom_churn.csv")
print(df["contract"].value_counts())
print(df["churn"].value_counts(normalize=True).round(3))
print(df.describe(include="object"))In 5 minutes we already know: 3,000 customers, 25 missing total_charges, 29% churned, and most customers are on monthly contracts. Write such notes down – they become the “Insights” slide of your project (Day 57).
Saving results
import pandas as pd
df = pd.read_csv("telecom_churn.csv")
monthly = df[df["contract"] == "Monthly"]
monthly.to_csv("monthly_customers.csv", index=False)
print("Saved", len(monthly), "rows;", round(len(monthly) / len(df) * 100, 1), "% of customers")
print(pd.read_csv("monthly_customers.csv").columns.tolist()[:5])🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
city, area_sqft and price_lakh from house_prices.csv and print the 3 largest houses.Show solution
import pandas as pd
h = pd.read_csv("house_prices.csv", usecols=["city", "area_sqft", "price_lakh"])
print(h.nlargest(3, "area_sqft"))loan_applications.csv. What share of applications were approved?Show solution
import pandas as pd
loans = pd.read_csv("loan_applications.csv")
print(loans.shape, loans.isna().sum().sum())
print(loans["approved"].mean().round(3))sales_data.csv into an Excel file with one sheet per region.Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
What is the first thing you do with a new dataset?
Check its size and a sample of rows, then info() for types and missing values, describe() for ranges and impossible values, nunique()/value_counts() for categories, and write down questions and data-quality issues before any modelling.
How do you read a file too big for memory with pandas?
Use usecols and suitable dtypes (category, int32) to shrink it, or read in chunks with chunksize and aggregate each chunk; for very large data use a database, Parquet files or tools like Polars/Spark.
Summary
- read_csv with usecols, nrows, parse_dates, dtype and na_values.
- read_excel / to_excel handle multi-sheet workbooks.
- json_normalize flattens API data.
- Checklist: shape → head → info → describe → isna/nunique → value_counts.
Day 12: select exactly the rows and columns you need with loc, iloc, boolean filters, query and sorting.
