What You Will Learn
- What a pandas DataFrame is and how to create one
- How to inspect data with
head,info,describe - Selecting columns and rows with
locandiloc - Reading data from CSV and JSON files
Why This Topic Matters
The DataFrame is the central object in pandas — every analysis revolves around it. Once you can create, inspect, and slice a DataFrame, you have the foundation for everything else in this phase: filtering, grouping, cleaning, and visualization.
Creating a DataFrame
The most common way: pass a dictionary where each key is a column name and each value is a list of that column's values.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"customer": ["Anita", "Ravi", "Mira", "Sam"],
"city": ["Mumbai", "Chennai", "Kolkata", "Mumbai"],
"amount": [500, 1200, 750, 900]
})
print(df)
Output:
order_id customer city amount
0 1 Anita Mumbai 500
1 2 Ravi Chennai 1200
2 3 Mira Kolkata 750
3 4 Sam Mumbai 900
The numbers on the left (0, 1, 2, 3) are the index — a label for each row. By default, pandas numbers rows from 0. You can set any column as the index, which is useful for lookups.
Inspecting a DataFrame
df.head() # first 5 rows
df.head(2) # first 2 rows
df.tail() # last 5 rows
df.shape # (4, 4) — 4 rows, 4 columns
df.columns # Index(['order_id', 'customer', 'city', 'amount'], dtype='object')
df.dtypes # data type of each column
df.info() # summary: shape, types, non-null counts
df.describe() # statistics for numeric columns
df.describe() output
order_id amount
count 4.000000 4.000000
mean 2.500000 837.500000
std 1.290994 302.081206
min 1.000000 500.000000
25% 1.750000 687.500000
50% 2.500000 825.000000
75% 3.250000 975.000000
max 4.000000 1200.000000
describe() gives count, mean, std, min, quartiles, max for every numeric column. In one call, you have a statistical summary. We explain these stats in lesson 29 and lesson 30.
Selecting Columns
df["customer"] # one column → returns a Series
df[["customer", "amount"]] # two columns → returns a DataFrame
df.customer # also works (attribute access) — but not for column names with spaces
Selecting Rows
By position — iloc
df.iloc[0] # first row
df.iloc[0:2] # rows 0 and 1 (Python slice: end exclusive)
df.iloc[0, 2] # row 0, column 2 → "Mumbai"
iloc = "integer location". Uses positions, like list indexing.
By label — loc
df.loc[0] # row with index label 0
df.loc[0:2] # rows 0 through 2 (inclusive!)
df.loc[0, "customer"] # row 0, column "customer" → "Anita"
df.loc[df["amount"] > 700] # rows where amount > 700 (filter)
loc = "label location". Uses index labels and column names. Slices are inclusive on both ends (unlike iloc).
df.loc[0:2] includes rows 0, 1, 2 (3 rows). df.iloc[0:2] includes rows 0, 1 (2 rows). The difference is intentional: loc is label-based (inclusive), iloc is position-based (Python slice rules, exclusive end).
Setting a Custom Index
df = df.set_index("order_id")
df.loc[1] # row where order_id == 1
df = df.reset_index() # bring order_id back as a regular column
Custom indexes make row lookups by ID fast and readable.
Reading Data from Files
CSV
df = pd.read_csv("orders.csv")
One line. pandas auto-detects column types, handles the header row, and returns a DataFrame. Options worth knowing:
pd.read_csv("orders.csv", sep=";") # semicolon separator
pd.read_csv("orders.csv", parse_dates=["ordered_at"]) # parse dates
pd.read_csv("orders.csv", na_values=["", "N/A"]) # treat these as NaN
pd.read_csv("orders.csv", dtype={"pin_code": str}) # force a column type
JSON
df = pd.read_json("orders.json")
For nested JSON (objects inside objects), use pd.json_normalize(data) to flatten it into a table. We touched on this in lesson 06.
From a SQL database
import sqlite3
conn = sqlite3.connect("mydb.sqlite")
df = pd.read_sql("SELECT * FROM orders WHERE amount > 500", conn)
pandas runs the SQL query and returns the result as a DataFrame. The bridge between SQL and Python — extremely common in real analytics workflows.
Adding and Removing Columns
df["tax"] = df["amount"] * 0.10 # new column
df["total"] = df["amount"] + df["tax"]
df = df.drop(columns=["tax"]) # remove column
df = df.drop(columns=["tax", "total"])
Vectorized operations apply to every row at once — no loops needed.
Exporting Data
df.to_csv("output.csv", index=False) # index=False avoids writing row numbers
df.to_json("output.json", orient="records", indent=2)
Always pass index=False to to_csv unless you specifically need the index saved.
Common Mistakes
- Confusing
locandiloc. Especially the slice behavior — loc is inclusive, iloc is exclusive at the end. - Selecting a column with
df.colwhen the name has spaces. Always usedf["col name"]for names with spaces or special characters. - Modifying a slice of a DataFrame.
df[df["amount"] > 500]["amount"] = 0silently fails. Usedf.loc[df["amount"] > 500, "amount"] = 0instead. - Forgetting
index=Falsewhen saving CSV. Otherwise the row numbers get written as an unnamed column. - Assuming column types are correct after read_csv. pandas guesses types from the first 1000 rows. Always check
df.dtypesafter loading.
Practical Exercise (15 minutes)
- Create the DataFrame above with the four orders.
- Use
df.head(),df.info(),df.describe()and read every line of output. - Select only the
customerandamountcolumns. - Use
ilocto get the first 2 rows. Uselocto get rows where amount > 700. - Add a
taxcolumn = amount × 0.10. - Save the result to CSV with
index=False. Open the CSV in a text editor to confirm it looks right.
Mini Challenge
Create a CSV file with at least 10 rows of fake sales data (use any cities, products, and amounts you like). Load it into pandas. Use df.describe() and df["column"].value_counts() to summarize it in three different ways. Write a one-paragraph "executive summary" of what the data tells you, based only on pandas output.
Key Takeaways
- Create a DataFrame from a dict of lists; load from CSV with
pd.read_csv. head,info,describeare your inspection toolkit.loc= by label (inclusive slices);iloc= by position (exclusive end).- Vectorized column math:
df["new"] = df["a"] + df["b"]. - Always pass
index=Falsetoto_csvunless you need the index.
Previously learned: Lesson 24 set up Python and introduced the basics.
Today: You met the DataFrame — pandas' central object.
Next: Lesson 26 shows you how to filter, sort, and group DataFrames — the SQL operations you already know, in Python.
FAQ
What is the difference between a Series and a DataFrame?
A Series is a single column of data (one-dimensional). A DataFrame is a table of multiple Series (two-dimensional). Selecting one column from a DataFrame returns a Series; selecting multiple columns returns a DataFrame.
Why does pandas use 0-based indexing?
Because Python uses 0-based indexing for lists, and pandas follows Python conventions. The first row is row 0, the second is row 1, and so on. This is the same as most programming languages but different from R or Excel (which are 1-based).
Comments
Comments
Post a Comment