Reading files#
Other readers:
| Source | Function |
|---|---|
| CSV | pd.read_csv("file.csv") |
| Excel | pd.read_excel("file.xlsx", sheet_name="Sales") (needs openpyxl) |
| JSON | pd.read_json("file.json") |
| SQL database | pd.read_sql("SELECT ...", connection) |
| Web table | pd.read_html(url) |
| Clipboard | pd.read_clipboard() - copy cells in Excel, then run |
Useful read_csv options:
pd.read_csv("file.csv",
parse_dates=["order_date"], # convert to dates
usecols=["order_id", "sales"],# read only some columns
dtype={"pincode": str}, # keep leading zeros
na_values=["NA", "-", ""], # treat these as missing
encoding="utf-8") # Hindi text etc.
In Jupyter/Colab, the last line of a cell is displayed automatically - you can just write df.head(). In scripts (and this editor) use print().
The first five commands on any new dataset#
किसी भी नए dataset को देखते ही ये 5 commands चलाएँ:
df.head()- शुरुआत की कुछ rows कैसी दिखती हैंdf.info()- कितने columns, किस type के, कहाँ खाली values हैंdf.describe()- numbers का min, max, औसत, quartilesdf.isna().sum()- हर column में कितनी खाली valuesdf.duplicated().sum()- कितनी duplicate rows
इसे data profiling कहते हैं - इससे 2 मिनट में dataset की पूरी तस्वीर मिल जाती है।
Exploring categories#
Quick questions with filters#
The .dt accessor for dates#
| Code | Gives |
|---|---|
df["order_date"].dt.year |
2025 |
.dt.month / .dt.month_name() |
10 / October |
.dt.day_name() |
Tuesday |
.dt.quarter |
4 |
.dt.to_period("M") |
2025-10 |
The .str accessor for text#
| Code | Does |
|---|---|
df["product"].str.contains("Laptop") |
True/False mask |
.str.upper(), .str.title(), .str.strip() |
clean text |
.str.split("-").str[1] |
part of a code (VM-2025-00811 → 2025) |
.str.len() |
length |
Selecting by data type#
df.select_dtypes("number").columns # numeric columns
df.select_dtypes("object").columns # text columns
Saving results#
result.to_csv("big_orders.csv", index=False)
result.to_excel("report.xlsx", sheet_name="Big orders", index=False) # needs openpyxl
index=False stops pandas from writing the 0, 1, 2... index as an extra column.
Summary#
pd.read_csv/read_excelload data; useparse_dates,usecols,dtype,na_values.- Profile every dataset:
head,info,describe,isna().sum(),duplicated().sum(). value_counts,nunique,uniqueexplore categories.- Filter with masks, use
.dtfor dates and.strfor text;nlargestfor top N. - Save with
to_csv/to_excel(index=False).