🏥
Real-world scenario
Nakuru clinic network: analyzing ante-natal care coverage

Esther works for a healthcare NGO in Nakuru, Kenya. She's analyzing clinic visit data across 12 Rift Valley clinics to report to donors about ante-natal care coverage. Every column in her data has a type that dictates what she can do with it—that's today's lesson.

42
Visits analyzed
12
Clinics covered
Q1 2026
Data period

The visual hero: understanding data types

Every DataFrame column has a type. Understanding these types is everything—your type determines what you can filter, aggregate, and analyze.

Clinic visits table with column types annotated
visit_id object date datetime64 clinic object patient_age int64 anc_visit int64 bp_systolic int64 bp_diastolic int64 status object
ANC0012026-01-04Nakuru Level 528112080normal
ANC0022026-01-04Molo Sub-County31212885high_bp
ANC0032026-01-05Njoro Health Centre25111575normal
ANC0042026-01-05Bahati Health Centre34313288high_bp
ANC0052026-01-06Elementaita Dispensary22111878normal
ANC0062026-01-06Naivasha Level 429212582normal
ANC0072026-01-07Nakuru Level 526111072normal
ANC0082026-01-07Molo Sub-County35413892referred
What this shows: The object columns (visit_id, clinic, status) are text and categorical—you can filter and count them. The int64 columns (age, blood pressure) are numbers—you can average, sum, and compare them. The datetime64 column (date) unlocks time-based filtering and grouping.

Series vs DataFrame: 1D vs 2D thinking

Pandas has two core data structures. A Series is a single column of labeled values (1D). A DataFrame is many columns stacked together (2D)—it's a spreadsheet.

Series: one column at a time

What it looks like
Name: bp
—————————
120
128
115
132
122
How you create it
series.py

DataFrame: the full table

What it looks like
clinicpatient_agebp_systolic
Nakuru L528120
Molo31128
Njoro25115
How you create it
dataframe.py
When to use each: A Series is a single variable (patient ages, blood pressures). A DataFrame is multiple related variables—use it when you have a real dataset with rows and columns. Almost all Pandas analysis starts with a DataFrame.

The 10 methods that carry 80% of the work

These 10 methods appear in 90% of real Pandas analysis. Master these and you've cracked data exploration.

Method What it does When to reach for it
.head() Shows first N rows (default 5) First thing: preview your data. Is it loaded right? Any parsing issues?
.tail() Shows last N rows Check the end of your dataset. Did imports finish? Any incomplete rows?
.info() Column names, types, non-null counts Audit your data structure. How many missing values per column? Wrong dtypes?
.describe() Mean, std, min, max, quartiles (numeric cols) Quick statistics. Is the range sensible? Outliers lurking?
.shape Tuple (rows, columns) How big is my dataset? (42 rows, 8 columns)
.columns List of all column names Remind yourself of available fields. Any typos in column names?
.dtypes Data type per column Sanity check. Is 'date' a datetime or string? Is 'amount' int or float?
.value_counts() Unique value counts (on a Series) How many visits per clinic? Which status appears most?
.isnull().sum() Missing value count per column Data quality check. Which columns have gaps?
.sample() Random N rows Quick sanity check on a big dataset. Spot weird patterns without reading all data.

Inspecting Esther's clinic data: picture first, code second

Let's apply these 10 methods to Esther's real clinic data. Each visual comes first—that's the lesson. Then we show the code that produced it.

📋
Clinic visits dataset to follow along
Save next to your notebook so pd.read_csv('clinic_visits.csv') works.

Step 1: .head() — preview the first 5 rows

Output from df.head()
visit_iddateclinicpatient_ageanc_visit_numberbp_systolicbp_diastolicstatus
ANC0012026-01-04Nakuru Level 528112080normal
ANC0022026-01-04Molo Sub-County31212885high_bp
ANC0032026-01-05Njoro Health Centre25111575normal
ANC0042026-01-05Bahati Health Centre34313288high_bp
ANC0052026-01-06Elementaita Dispensary22111878normal
What this shows: The first 5 clinic visits loaded correctly. Dates are parsed, ages are numbers, status values make sense. Good starting point.
code1.pyPandas: preview data with head()

Step 2: .info() — audit structure and missing data

Output from df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 42 entries, 0 to 41
Data columns (total 8 columns):

# Column Non-Null Count Dtype
--- ------ -------------- -----
0 visit_id 42 non-null object
1 date 42 non-null object
2 clinic 42 non-null object
3 patient_age 42 non-null int64
4 anc_visit_number 42 non-null int64
5 bp_systolic 42 non-null int64
6 bp_diastolic 42 non-null int64
7 status 42 non-null object

dtypes: int64(4), object(4)
memory usage: 3.0 KB
What this shows: 42 rows, 8 columns. All columns are non-null (no missing data). Note: date is object (string), not datetime64—Esther will need to parse it with pd.to_datetime() to unlock date operations.
code2.pyPandas: audit data structure

Step 3: .describe() — numeric summary statistics

Output from df.describe()
patient_ageanc_visit_numberbp_systolicbp_diastolic
count42.042.042.042.0
mean28.31.9123.181.8
std4.21.18.56.1
min22.01.0110.072.0
25%25.01.0118.078.0
50%28.52.0123.082.0
75%31.02.0130.086.0
max36.04.0142.095.0
What this shows: Patient ages range 22–36 (typical ante-natal). Average BP is 123/82 (normal range). Visits 1–4 (repeat attendees). One outlier at 142 systolic (flagged for follow-up).
code3.pyPandas: numeric statistics

Step 4: .value_counts() — clinic visit distribution

Output: visits per clinic
Visits by clinic (value_counts)
Horizontal bar chart showing clinic visit counts by facility from value_counts operation
What this shows: Nakuru Level 5 dominates with 8 visits (most accessible facility). Smaller clinics see 2–6 visits. This distribution tells Esther where to focus follow-up training.
code4.pyPandas: count unique values

Selecting data: .loc vs .iloc

Pandas has two ways to select rows and columns. .loc uses labels (column names, row index). .iloc uses integer positions (0, 1, 2...).

Method Selects by Example
.loc Label (column name, condition) df.loc[df['age'] > 25] — rows where age > 25
.iloc Integer position (0, 1, 2...) df.iloc[0:5] — rows 0 through 4 by position
.loc with columns Combine row + column selection df.loc[df['status']=='normal', ['clinic','age']]
.iloc mixed Position-based rows + columns df.iloc[0:10, [0,2,5]] — first 10 rows, columns 0, 2, 5

Real example: filter by condition and select columns

Output: first-time visits (anc_visit_number == 1) with age & clinic only
patient_ageclinic
28Nakuru Level 5
25Njoro Health Centre
22Elementaita Dispensary
26Nakuru Level 5
24Njoro Health Centre
code5.pyPandas: filter with loc

Quick filter patterns: the 5 you'll use daily

These five patterns cover 95% of real filtering. Bookmark this section.

Pattern Code Result
Filter by single value df[df['status'] == 'normal'] Rows where status is exactly 'normal'
Filter by range df[(df['patient_age'] >= 25) & (df['patient_age'] <= 35)] Ages 25–35 inclusive
Filter by list df[df['status'].isin(['normal', 'high_bp'])] Either normal or high_bp status
Filter by string contains df[df['clinic'].str.contains('Nakuru')] Clinics with 'Nakuru' in the name
Filter by null df[df['bp_systolic'].isnull()] Rows with missing BP
code6.pyPandas: filter patterns

Where you see this in the real world

Industries & use cases

🏥
Healthcare & NGO M&E
Analyze patient records, track immunization rates by clinic, report coverage metrics to donors like Esther does
📱
Telecom Operations
Inspect call logs, filter by duration/region, count unique users, describe churn rates per region
🛍️
E-commerce Analytics
Preview order data, check for nulls, describe order values, filter by date range and city
🏦
Fintech Fraud Detection
Inspect transactions, .info() to audit dtypes, filter by amount threshold, describe volume by branch

How this connects to AI & ML

Every ML pipeline starts here. You load data with pd.read_csv(), inspect with .head() and .info(), filter and clean it with .loc/.iloc, then feed it to scikit-learn or TensorFlow. Before you can train a model to predict high-risk pregnancies, you need to understand your data—that's what these methods do.

data inspection feature filtering data validation exploratory analysis

Mini Challenge

Task: Load clinic_visits.csv. Group by clinic and calculate median BP systolic per clinic. Which clinic has the highest median BP? Also count how many visits each clinic had. Hint: use .groupby('clinic')[['bp_systolic', ...]].agg().

Hint: df.groupby('clinic')['bp_systolic'].median().sort_values(ascending=False) will show you medians by clinic sorted high to low.

Interview questions

A Series is a single column of data (1D)—think of one variable like patient ages. A DataFrame is multiple columns (2D)—like an Excel sheet with rows and columns. Series have a name; DataFrames have column names.
.head() only shows first 5 rows; it hides problems later in the file. .info() shows: (1) total row count, (2) data types per column, (3) missing values. It catches dtype mismatches (date stored as string) and nulls that .head() wouldn't reveal.
It filters rows where age > 25 (condition is df['age'] > 25), then selects only the 'name' and 'clinic' columns. The comma separates row condition from column selection. Result is a subset DataFrame with 2 columns.
To count missing values per column. .isnull() returns True/False for each cell; .sum() counts the Trues. It's a data quality check—you want to know which columns have gaps before analyzing.
Because and is a Python operator that works on single booleans, not arrays. Pandas uses & (bitwise AND) for element-wise comparison. Also, parentheses are required around each condition because & has higher precedence than comparison operators.

Test your knowledge

Question 1 of 5
What does df.shape return?
Question 2 of 5
Which method shows you missing values per column?
Question 3 of 5
What does df['clinic'].value_counts() return?
Question 4 of 5
What's the main difference between .loc and .iloc?
Question 5 of 5
Why must you use & instead of and in df[(df['col'] > 5) & (df['col2'] < 10)]?
0
/5
Well done! You've mastered pandas fundamentals.

Cheatsheet: quick reference

Task Code Returns
Load CSV df = pd.read_csv('data.csv') DataFrame from file
First N rows df.head(5) First 5 rows
Last N rows df.tail(3) Last 3 rows
Row & column count df.shape Tuple (rows, cols)
Column names df.columns Index of column names
Data types df.dtypes Type per column
Full audit df.info() Types, nulls, memory
Numeric stats df.describe() Count, mean, std, min, max, quartiles
Unique value counts df['col'].value_counts() Series of counts
Missing values df.isnull().sum() Null count per column
Random sample df.sample(5) 5 random rows
Filter by condition df[df['age'] > 25] Rows where age > 25
Filter & select columns df.loc[cond, ['col1','col2']] Filtered rows, 2 columns
Select by position df.iloc[0:10, 0:5] First 10 rows, first 5 columns

Common pitfalls

Forgetting to call the method: df.head vs df.head()
df.head returns the method object (not data). Always add parentheses: df.head(). Same for .info(), .describe(), etc.
Using and instead of & in multi-condition filters
WRONG: df[df['age'] > 25 and df['status'] == 'normal']
RIGHT: df[(df['age'] > 25) & (df['status'] == 'normal')]
Parentheses required around each condition.
Confusing .describe() with .info()
.describe() = numeric stats (mean, std, min, max). .info() = column types, non-null counts, memory. Use .describe() to understand data ranges; use .info() to audit structure.
Dates stored as strings instead of datetime64
If df.info() shows date: object (string) when you expected dates, convert: df['date'] = pd.to_datetime(df['date']). Then you can filter by date ranges.
Assuming .head() means your data is clean
Always run .info(), .describe(), .isnull().sum() to audit the full dataset. First 5 rows can hide problems in rows 50–500.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

Ready to go deeper?

Join the Best AI Program: The AI-Era Analyst — 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Analyst →