3.2. Pandas, Data Cleaning, and Introductory EDA#
Week 2 reading · About 20–25 minutes
Suppose you’re helping a campus club choose a place for its next study session. You have feedback about a few study spaces. Which spaces did people like? How long did they stay? Before answering, you need to understand what the table represents and decide what to do with its messy entries.
This chapter walks through that process with complete examples and their outputs. There is nothing to submit here. Read it before Lab 01, or use it as a reference while working on the lab. The study-space data is fictional and different from the lab’s event survey, so you can practice the same ideas on your own.
By the end, you should be able to load a table, select and change data, explain a cleaning decision, and support an observation with a summary and a limitation. We focus on tables this week; plotting and feature engineering come next week.
3.2.1. From a CSV file to a DataFrame#
Pandas is a Python library for working with labeled data. A DataFrame is a two-dimensional table: rows represent observations, and columns represent variables. A Series is a one-dimensional collection with an index, such as a single column. Different columns can have different data types.
Our CSV contains one response about one visit per row. visit_id identifies a visit,
not necessarily a unique person: the same person could have visited more than once.
This distinction matters when deciding what counts as a duplicate and what our
results can say about students.
Column |
Meaning |
|---|---|
|
Identifier that should occur once per recorded visit |
|
Study space visited |
|
Reported duration in minutes; must be positive |
|
Satisfaction from 1 (lowest) to 5 (highest) |
A CSV stores a table as comma-separated text. pd.read_csv() reads that file
into a DataFrame and infers types. The alias pd is a convention, not a special
Python keyword. The CSV sits next to this notebook; relative paths are interpreted
from the running notebook’s working directory.
If you run this reading yourself, keep the example CSV next to the notebook. On the website, all example outputs are already shown.
import pandas as pd
visits = pd.read_csv("study_space_visits.csv")
visits.head()
| visit_id | location | minutes | rating | |
|---|---|---|---|---|
| 0 | 201 | North Library | 60 | 4.0 |
| 1 | 202 | student union | 30 | 3.0 |
| 2 | 203 | Quiet Room | 90 | 5.0 |
| 3 | 204 | north library | unknown | 4.0 |
| 4 | 205 | Student Union | 45 | NaN |
head() shows the first five rows by default. visits.head(3) would show three;
visits.tail(3) would show the last three. A preview is useful, but it cannot tell
us everything about a dataset. A problem may be hiding in a later row.
Pandas also assigns row index labels. Here the index starts at 0, while
visit_id is an ordinary column. An index need not be consecutive integers, and
sorting a table does not automatically renumber its labels.
print("Rows and columns:", visits.shape)
print("Column names:", visits.columns.tolist())
visits.info()
Rows and columns: (11, 4)
Column names: ['visit_id', 'location', 'minutes', 'rating']
<class 'pandas.DataFrame'>
RangeIndex: 11 entries, 0 to 10
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 visit_id 11 non-null int64
1 location 11 non-null str
2 minutes 11 non-null str
3 rating 10 non-null float64
dtypes: float64(1), int64(1), str(2)
memory usage: 484.0 bytes
The table has 11 rows and 4 columns. info() reports each column’s type and number
of non-missing entries. minutes is stored as text because one entry says unknown.
Being able to read a file does not mean its values have the types we want!
Depending on the pandas version, text columns may display as object, str, or
string. Inspect actual values before deciding how to convert them.
Notice shape has no parentheses: it is an attribute containing information.
head() and info() are methods that perform an operation. Calling
visits.shape() causes an error because the stored tuple is not a function.
3.2.2. Select the data you need#
3.2.2.1. One column or several?#
Use a column name in brackets to select a Series. Put a list of names inside those brackets to select a DataFrame, even if the list contains only one name. The distinction matters because some operations return different shapes.
ratings = visits["rating"] # Series
selected = visits[["location", "rating"]] # DataFrame
selected.head(3)
| location | rating | |
|---|---|---|
| 0 | North Library | 4.0 |
| 1 | student union | 3.0 |
| 2 | Quiet Room | 5.0 |
3.2.2.2. Labels with .loc, positions with .iloc#
.loc[rows, columns] selects by label or by a condition. .iloc[rows, columns]
selects by integer position. To make the difference visible, temporarily use
visit_id as the index. This creates another table; it does not change visits.
by_visit = visits.set_index("visit_id")
print("Visit labeled 203:")
print(by_visit.loc[203, ["location", "rating"]])
print("\nFirst row by position:")
print(by_visit.iloc[0])
Visit labeled 203:
location Quiet Room
rating 5.0
Name: 203, dtype: object
First row by position:
location North Library
minutes 60
rating 4.0
Name: 201, dtype: object
by_visit.loc[203] refers to the label 203, not the 204th row. by_visit.iloc[0]
refers to whichever row is first. For slices, .iloc[0:3] includes positions
0, 1, and 2; label slices with .loc include the ending label when present.
3.2.2.3. Filter rows with Boolean conditions#
A comparison such as visits["rating"] >= 4 produces one Boolean value per row.
This is often called a mask. Supply the mask to .loc to keep matching rows.
high_ratings_raw = visits.loc[
visits["rating"] >= 4,
["visit_id", "location", "rating"]
]
high_ratings_raw
| visit_id | location | rating | |
|---|---|---|---|
| 0 | 201 | North Library | 4.0 |
| 2 | 203 | Quiet Room | 5.0 |
| 3 | 204 | north library | 4.0 |
| 5 | 206 | quiet room | 6.0 |
| 6 | 207 | NORTH LIBRARY | 5.0 |
| 8 | 209 | Quiet Room | 4.0 |
| 9 | 210 | North Library | 4.0 |
Look closely: this includes a rating of 6. The code correctly applied our condition, but the result contains an invalid observation. Correct syntax does not guarantee a meaningful answer. We’ll fix the data before interpreting it.
To combine conditions, use & for and, | for or, and ~ for not.
Put each comparison in parentheses. Python’s and and or do not perform these
row-by-row operations on a Series.
3.2.3. EDA starts with questions and a data audit#
Exploratory data analysis (EDA) is the process of investigating a dataset’s structure, quality, distributions, and relationships. It helps us decide which questions the data can answer. Cleaning and EDA are iterative: a summary may reveal a problem, and fixing the problem may change the summary.
Start by asking: What does one row represent? Who or what is missing? Which values are plausible? Are categories recorded consistently? Then use pandas to look for evidence.
print("Missing values per column:")
print(visits.isna().sum())
print("\nExact repeated rows after their first appearance:", visits.duplicated().sum())
print("\nRecorded location labels:")
print(visits["location"].value_counts(dropna=False))
Missing values per column:
visit_id 0
location 0
minutes 0
rating 1
dtype: int64
Exact repeated rows after their first appearance: 1
Recorded location labels:
location
student union 3
North Library 2
Quiet Room 2
north library 1
Student Union 1
quiet room 1
NORTH LIBRARY 1
Name: count, dtype: int64
.isna() marks missing entries; summing those Booleans counts them. It detects
blank ratings, but the literal text unknown in minutes is not automatically
missing here. Likewise, inconsistent capitalization creates separate categories.
The duplicate count says one entire row is repeated.
A zero missing-value count is therefore not proof that a column is clean. Inspect unusual values, types, and the meaning of the variable as well.
3.2.4. Clean carefully, and preserve the raw data#
Keep an unchanged source table so you can revisit your decisions. Most methods below return a new result; assigning that result is how we keep a change.
3.2.4.1. Standardize categories#
Surrounding spaces and capitalization distinguish strings in Python even when
they refer to the same place. .str gives access to string operations across a
Series. Here we strip whitespace and lowercase the location names.
clean = visits.copy()
clean["location"] = clean["location"].str.strip().str.lower()
clean["location"].value_counts()
location
north library 4
student union 4
quiet room 3
Name: count, dtype: int64
Standardization is a decision about meaning. Lowercasing works for these names,
but it does not fix misspellings or tell us whether two differently named buildings
are actually the same place. If needed, a documented .replace() mapping can
handle known synonyms. Don’t merge categories just because they look similar.
3.2.4.2. Remove confirmed duplicate records#
The repeated row is an accidental copy of the same visit, so keeping it would count that visit twice. Remove exact duplicate rows, then inspect any remaining repeated IDs for conflicting records.
clean = clean.drop_duplicates()
print("Unique visit records:", len(clean))
clean.loc[clean.duplicated(subset="visit_id", keep=False)]
Unique visit records: 10
| visit_id | location | minutes | rating |
|---|
There are now 10 records; the empty table confirms no repeated visit IDs remain.
Using .drop_duplicates(subset="visit_id") immediately could silently discard
conflicting feedback. Also, different visits can legitimately have identical
ratings and durations. Deduplication depends on what makes a record unique.
3.2.4.3. Convert types, then apply validity rules#
pd.to_numeric() converts numeric-looking text into numbers. With
errors="coerce", entries it cannot parse become missing. Inspect the entries
that failed conversion so a typo or unexpected format does not disappear unnoticed.
numeric_minutes = pd.to_numeric(clean["minutes"], errors="coerce")
conversion_failed = clean["minutes"].notna() & numeric_minutes.isna()
clean.loc[conversion_failed, ["visit_id", "minutes"]]
| visit_id | minutes | |
|---|---|---|
| 3 | 204 | unknown |
clean["minutes"] = numeric_minutes
invalid_duration = clean["minutes"] <= 0
invalid_rating = (clean["rating"] < 1) | (clean["rating"] > 5)
clean.loc[invalid_duration, "minutes"] = float("nan")
clean.loc[invalid_rating, "rating"] = float("nan")
clean.isna().sum()
visit_id 0
location 0
minutes 2
rating 2
dtype: int64
We now have two missing durations and two missing ratings. The invalid values became missing because we cannot infer their intended values. We kept the rows: their other information can still be useful.
This is different from automatically removing outliers. A 120-minute study visit is long but plausible; a negative duration violates our definition. Unusual observations deserve investigation, not automatic deletion.
Use .isna() or .notna() to detect missingness rather than comparing with NaN.
Pandas uses different missing-value representations depending on the type, and
equality comparisons do not reliably identify them.
3.2.5. Missing values require a choice#
There are three common responses, each with tradeoffs:
Approach |
When it can help |
What to watch for |
|---|---|---|
Leave missing values as missing |
A summary can use the available observations |
Different summaries may have different denominators |
Drop rows for a particular analysis |
That analysis needs a specific observed value |
Missingness may be systematic; dropping rows can bias results |
Fill with an assumed value |
You have a justified strategy for the task |
Filled values are estimates, not observations |
A missing rating is not a zero rating. Our example will leave ratings missing. Means skip missing values by default, so we must report counts alongside means. If we needed a table containing only observed ratings, we could create one explicitly:
rated_visits = clean.dropna(subset=["rating"])
print("All visits:", len(clean))
print("Visits with a valid rating:", len(rated_visits))
All visits: 10
Visits with a valid rating: 8
Using clean.dropna() without subset would discard rows missing any column,
including duration—even for a question concerned only with ratings.
To see how filling works, make a separate example copy and replace missing durations with the median observed duration. Record which values were missing before filling. The median is less sensitive to extreme values than the mean, but that does not make this a universally appropriate method.
filled_example = clean.copy()
filled_example["minutes_were_missing"] = filled_example["minutes"].isna()
median_minutes = filled_example["minutes"].median()
filled_example["minutes"] = filled_example["minutes"].fillna(median_minutes)
print("Median used:", median_minutes)
filled_example.loc[
filled_example["minutes_were_missing"],
["visit_id", "minutes", "minutes_were_missing"]
]
Median used: 52.5
| visit_id | minutes | minutes_were_missing | |
|---|---|---|---|
| 3 | 204 | 52.5 | True |
| 8 | 209 | 52.5 | True |
The filled durations are 52.5 minutes. They should not be described as times
students actually reported. Filling also changes the distribution, potentially
making it look less variable. We will continue exploring clean, which retains
missing durations, rather than silently substituting filled_example.
Pause and think: If people who disliked a space are less likely to leave a rating, would dropping missing ratings solve that problem? No—the observed ratings could still overrepresent happy visitors. Cleaning cannot recover feedback we never collected.
3.2.6. Manipulate the cleaned table#
3.2.6.1. Add a column using a calculation#
Assigning to a new column name adds it to the DataFrame. Arithmetic acts on all rows at once; there is no need to write a loop for this conversion.
clean["hours"] = clean["minutes"] / 60
clean[["visit_id", "minutes", "hours"]].head()
| visit_id | minutes | hours | |
|---|---|---|---|
| 0 | 201 | 60.0 | 1.00 |
| 1 | 202 | 30.0 | 0.50 |
| 2 | 203 | 90.0 | 1.50 |
| 3 | 204 | NaN | NaN |
| 4 | 205 | 45.0 | 0.75 |
Missing durations remain missing after conversion. We can now ask for recorded
visits lasting at least an hour with ratings of at least 4. The .notna() check
makes our intended treatment of missing duration explicit.
long_and_positive = clean.loc[
clean["minutes"].notna()
& (clean["minutes"] >= 60)
& (clean["rating"] >= 4),
["visit_id", "location", "minutes", "rating"]
]
long_and_positive.sort_values("minutes", ascending=False)
| visit_id | location | minutes | rating | |
|---|---|---|---|---|
| 2 | 203 | quiet room | 90.0 | 5.0 |
| 6 | 207 | north library | 75.0 | 5.0 |
| 0 | 201 | north library | 60.0 | 4.0 |
.sort_values() reorders rows; ascending=False puts larger values first.
It doesn’t modify long_and_positive unless we assign the returned table.
An omitted visit might have a low rating, a short duration, or missing information:
not appearing here doesn’t mean a visitor was unhappy.
For changing selected cells, use a single .loc assignment, as we did when
marking invalid values. Avoid chained assignments such as
clean["rating"][some_mask] = value, which are unreliable across pandas versions.
3.2.7. Summarize distributions and compare groups#
3.2.7.1. Describe numeric variables#
.describe() reports non-missing count, mean, standard deviation, minimum,
quartiles, and maximum. The 50% value is the median. Counts tell you how many
observations support each column’s statistics.
clean[["minutes", "rating"]].describe()
| minutes | rating | |
|---|---|---|
| count | 8.000000 | 8.000000 |
| mean | 60.625000 | 3.875000 |
| std | 33.105621 | 0.991031 |
| min | 20.000000 | 2.000000 |
| 25% | 41.250000 | 3.750000 |
| 50% | 52.500000 | 4.000000 |
| 75% | 78.750000 | 4.250000 |
| max | 120.000000 | 5.000000 |
Only eight visits have valid durations, and only eight have valid ratings.
These are not necessarily the same eight visits. Also, numeric storage alone
doesn’t make a variable suitable for averaging: the mean visit_id would tell
us nothing useful about study spaces.
For categories, use counts. value_counts() answers how often each category
appears, not how many people used the space across campus.
clean["location"].value_counts()
location
north library 4
student union 3
quiet room 3
Name: count, dtype: int64
3.2.7.2. Group, summarize, compare#
groupby("location") splits rows into groups. Select a variable and apply a
summary such as .mean() or .median() to each group. .agg() computes multiple
summaries. Here count counts non-missing ratings, not all rows.
rating_summary = clean.groupby("location")["rating"].agg(["count", "mean"])
rating_summary.sort_values("mean", ascending=False)
| count | mean | |
|---|---|---|
| location | ||
| quiet room | 2 | 4.50 |
| north library | 4 | 4.25 |
| student union | 2 | 2.50 |
Quiet Room has the highest observed mean rating, 4.5, but that mean comes from only two valid ratings. North Library’s mean of 4.25 comes from four. This is an observation about these records, not a confident ranking for all students. Ratings are ordered categories; a mean is a convenient summary here, but it assumes the steps between ratings can be treated as equally spaced.
To keep the denominator visible, compare total records (size) with
non-missing values (count). Named aggregation gives readable column names.
location_summary = clean.groupby("location").agg(
total_visits=("visit_id", "size"),
rated_visits=("rating", "count"),
mean_rating=("rating", "mean"),
median_minutes=("minutes", "median"),
)
location_summary.round(2)
| total_visits | rated_visits | mean_rating | median_minutes | |
|---|---|---|---|---|
| location | ||||
| north library | 4 | 4 | 4.25 | 60.0 |
| quiet room | 3 | 2 | 4.50 | 105.0 |
| student union | 3 | 2 | 2.50 | 30.0 |
Student Union and Quiet Room each have three recorded visits but only two valid ratings. Their average ratings exclude missing feedback. The median duration may be based on a different set of visits. Include these details when communicating results rather than presenting a number without its context.
3.2.8. Turn the output into a careful finding#
A useful EDA finding combines a question, evidence, and a limitation:
In these fictional responses, Quiet Room had the highest mean rating (4.5), based on two valid ratings from three visits. This small set of visits was not sampled to represent all students, and missing feedback could affect the comparison. We would collect more responses before using it to choose a study space for everyone.
We also cannot conclude that staying longer causes higher satisfaction. People might stay longer because they already like a space; other factors might affect both duration and rating. EDA helps generate questions and hypotheses, not automatically establish causal explanations.
The workflow is repeatable: understand the rows → inspect → clean with reasons → summarize → interpret. In a real project, keep your cleaning code and note the rules you applied so another person can reproduce the analysis.
3.2.8.1. Quick reference for Lab 01#
Goal |
Pattern |
|---|---|
Read a CSV |
|
Preview / inspect |
|
Select a column / table |
|
Select by label / position |
|
Filter |
|
Combine conditions |
|
Find missing entries |
|
Standardize text |
|
Convert numeric text |
|
Remove exact duplicates |
|
Drop for one required column |
|
Fill with an assumed value |
|
Sort descending |
|
Summarize |
|
Compare groups |
|
Return to the Week 2 course schedule for the lab. For another worked introduction, see the existing Tabular Data in Pandas reading.
3.2.8.2. Further reading and source notes#
This chapter adapts the topics in the course’s Spring 2026 Intro to Pandas and EDA & Data Visualization reading notebooks into one Week 2 walkthrough, with a new fictional dataset. Those original notebooks and the existing textbook chapters remain available in their repositories.