pandas Exercises
Fill in the blanks to check your knowledge. Each exercise belongs to a lesson.
pandas Introduction
Exercise
Import pandas with its usual alias.
import pandas as pandas Get Started
Exercise
Install command.
pip pandas
Series versus DataFrame
Exercise
Create a table.
pd.({"a": [1]})
Shape, dtypes and info
Exercise
Rows and columns.
df.head, tail and sample
Exercise
First rows.
df.(2)
Create a Series
Exercise
Create a Series from a list.
pd.([1, 2, 3])
Series Index and Labels
Exercise
Get by position.
s.[0]
Series Arithmetic
Exercise
Add 5 to every value.
s 5
Series Statistics
Exercise
Average.
s.()
Data Types
Exercise
See the type.
s.Apply and Map
Exercise
Square each item.
s.(lambda x: x * x)
Series with a Custom Index
Exercise
Label access.
s.["Ada"]
Series Arithmetic
Exercise
Add elementwise.
a b
Series Methods
Exercise
Count each value.
s.()
apply and map
Exercise
Run a function.
s.(len)
Boolean Series
Exercise
Filter rows.
df[df["score"] 80]
Describing Data
Exercise
Summary.
s.()
Create a DataFrame
Exercise
Build from rows.
pd.DataFrame([[1, 2]], =["a", "b"])
Shape, Columns and Types
Exercise
Get rows and columns.
df.Head, Tail and Sample
Exercise
Show the first 3 rows.
df.head()
Summary Statistics
Exercise
Summarize the table.
df.()
Add and Change Columns
Exercise
Add a column named x.
df["x"] 1
Drop Rows and Columns
Exercise
Drop a column.
df.drop(=["age"])
Rename Labels
Exercise
Rename a column.
df.(columns={"a": "b"})
Sort Values
Exercise
Sort descending.
df.sort_values("age", ascending=)
Set and Reset the Index
Exercise
Use name as index.
df.set_index("")
Iterate Over Rows
Exercise
Loop over rows.
df.()
Creating DataFrames
Exercise
From records.
pd.DataFrame([{"a": 1}, ])
Adding and Removing Columns
Exercise
Remove a column.
df.(columns=["a"])
Renaming
Exercise
Rename columns.
df.(columns={})
Sorting
Exercise
Sort by a column.
df.sort_values()
Unique and Duplicates
Exercise
Remove repeats.
df.()
Setting the Index
Exercise
Use name as index.
df.("name")
Iterating Rows
Exercise
Fast iteration.
df.()
Totals by Row and Column
Exercise
Row totals.
df.sum(=1)
where and clip
Exercise
Limit a range.
s.(0, 100)
Select Columns
Exercise
Select one column.
df[""]
Select with loc
Exercise
Select by label.
df.[0, "name"]
Select with iloc
Exercise
First row.
df.iloc[]
Filter Rows
Exercise
Rows with score above 80.
df[df["score"] 80]
Combine Conditions
Exercise
And operator.
(a > 1) (b > 1)
isin and between
Exercise
Check membership.
df["city"].(["Lagos"])
query and where
Exercise
Filter by text.
df.("age > 30")
Fast Scalar Access
Exercise
Read one cell by label.
df.[0, "age"]
Selecting Columns
Exercise
Two columns.
df[]
loc and iloc
Exercise
By position.
df.[0, 0]
Filtering with Conditions
Exercise
And operator.
(a) (b)
isin and between
Exercise
Range test.
df.score.(70, 80)
query
Exercise
Filter by text.
df.("score > 80")
nlargest and nsmallest
Exercise
Top two.
df.(2, "score")
copy and Chained Assignment
Exercise
Safe copy.
df[mask].()
Find Missing Values
Exercise
Count missing per column.
df.isna().()
Fill Missing Values
Exercise
Fill with zero.
s.(0)
Drop Missing Values
Exercise
Drop incomplete rows.
df.()
Find Duplicates
Exercise
Remove duplicates.
d.()
Change Data Types
Exercise
Convert to float.
s.("float64")
Replace Values
Exercise
Replace a value.
s.replace(1, )
String Methods
Exercise
Make lowercase.
s.str.()
apply on Rows and Columns
Exercise
Apply to rows.
df.apply(f, axis=)
Clip, Round and Cut Values
Exercise
Limit to 0..10.
s.(0, 10)
Missing Values
Exercise
Find missing.
df.()
Filling Strategies
Exercise
Forward fill.
s.()
Changing Types
Exercise
Convert to number.
pd.(s)
String Methods
Exercise
Lower case.
s.str.()
replace
Exercise
Swap a value.
s.("a", "b")
Spotting Outliers
Exercise
Quartile.
s.(0.25)
Binning with cut
Exercise
Bins.
pd.(s, bins=3)
Categorical Data
Exercise
Category type.
astype("")
Read CSV
Exercise
Read a CSV.
pd.("data.csv")
Write CSV
Exercise
Leave out the index.
df.to_csv("o.csv", index=)
Read and Write JSON
Exercise
Write JSON records.
df.to_json(orient="")
Excel and Other Formats
Exercise
Read Excel.
pd.("a.xlsx")
Read from SQL
Exercise
Write to SQL.
df.("t", con)
CSV Round Trip
Exercise
Write a CSV.
df.("f.csv")
read_csv Options
Exercise
Change the separator.
read_csv(f, =";")
JSON Input and Output
Exercise
Records format.
to_json(orient="")
Excel and SQL Notes
Exercise
Read from a database.
pd.("select 1", con)
Working with Dates
Exercise
Month number.
s.dt.resample
Exercise
Monthly totals.
s.("MS").sum()
Display Options
Exercise
Change an option.
pd.("k", v)
apply on Rows
Exercise
Per row.
df.apply(f, =1)
Group By
Exercise
Group by city.
df.("city")
Aggregate Several Ways
Exercise
Several statistics.
df.groupby("c").(["sum", "mean"])
Count Values
Exercise
Count distinct values.
df["city"].()
Pivot Tables
Exercise
Build a pivot table.
df.(index="a", values="b")
Concatenate
Exercise
Stack tables.
pd.([a, b])
Merge (SQL style join)
Exercise
Join on a key.
a.merge(b, on="")
Left, Right and Outer Joins
Exercise
Keep all left rows.
a.merge(b, on="id", how="")
join and Index Alignment
Exercise
Join by index.
a.(b)
Crosstab and Counting Pairs
Exercise
Count combinations.
pd.(a, b)
Dates and Times
Exercise
Parse dates.
pd.("2024-05-01")
Date Ranges
Exercise
Make 3 days.
pd.date_range("2024-01-01", =3)
groupby
Exercise
Group rows.
df.("country")
Several Aggregations
Exercise
Many functions.
.(["min", "max"])
pivot_table
Exercise
Grid summary.
df.(index="c")
merge
Exercise
Join on a key.
a.(b, on="id")
concat
Exercise
Stack rows.
pd.([a, b])
Cumulative and Rolling
Exercise
Running total.
s.()
rank and shift
Exercise
Move down one row.
s.(1)
Frequency Tables
Exercise
Pair counts.
pd.(a, b)
MultiIndex
Premium exercise. See plans
transform and filter in Groups
Premium exercise. See plans
Rolling Windows
Premium exercise. See plans
Resample Time Series
Premium exercise. See plans
Melt and Stack
Premium exercise. See plans
Categorical Data
Premium exercise. See plans
Shift, Diff and Percent Change
Premium exercise. See plans
Rank and Quantile Bins
Premium exercise. See plans
Split and Explode Lists
Premium exercise. See plans
merge_asof and Nearest Matches
Premium exercise. See plans
Weighted and Custom Windows
Premium exercise. See plans
Rank Within Groups
Premium exercise. See plans
Method Chaining and pipe
Premium exercise. See plans
Reduce Memory
Premium exercise. See plans
Vectorize Instead of Looping
Premium exercise. See plans
Copy on Write
Premium exercise. See plans
Testing DataFrames
Premium exercise. See plans
pandas for SQL Users
Premium exercise. See plans
Plotting with pandas
Premium exercise. See plans
A Small Data Cleaning Project
Premium exercise. See plans
pandas Best Practices
Premium exercise. See plans