Data Exploration
CMSC 320: Introduction to Data Science
2026
�
Lecture - 09
– FARDINA FATHMIUL ALAM
(fardina@umd.edu)
�
Topics to Cover
Chapter 9 in Textbook
Exploratory data analysis (EDA) Checklist
Why have a lecture on data exploration?
When we start our process, all we have is a CSV, with no idea what we have.
Exploratory Data Analysis refers to the critical process of performing initial investigations on data so as to
Exploratory data analysis (EDA)
Before making inferences from data it is essential to examine all your variables.
Why?
To listen to the data:
- to catch mistakes
- to see patterns in the data
- to find violations of statistical assumptions
- to generate hypotheses
…and because if you don’t, you will have trouble later
It is a good practice to understand the data first and try to gather as many insights from it.
EDA is all about making sense of data in hand, before getting them dirty with it.
Aim of Exploratory data analysis (EDA)
EDA provides a structured process for approaching this scenario. Involves a series of steps and techniques to systematically explore the data to
This process ensures that you don't miss critical information and can make informed decisions about subsequent analyses or modeling.
EDA also emphasizes the importance of data vis.
Use suitable visualizations and statistical tests to support findings.
3 steps to understand the Cycle of EDA
Generate questions about your data
Use what you learn to refine your questions and or generate new questions
Search for answers by visualizing, transforming, and modeling your data
03
01
02
Rinse and repeat (until you publish a paper or your boss approved it!)
HISTORY
Depending on the number of columns we are analyzing we can divide EDA into three types.
Type | Variables | Methods | Example |
Univariate | Focuses on one variable. | Histogram, Box Plot, Bar Chart, Summary Stats (mean, median, variance, etc.) | Distribution of student ages in a class |
Bivariate | Examines relationships between two variables.� | Scatter plots (continuous variables), correlation & covariance (strength/association), cross-tabulation (categorical variables), line graphs (time trends), heatmap (graphical representation� | Relationship between advertising spend and revenue. |
Multivariate | Looks at relationships among three or more variables. | pair plots (multiple relationships), PCA (dimensionality reduction), spatial analysis (maps), time series analysis (patterns/trends over time), cluster analysis etc. | Predicting house prices using size, location, and number of rooms. |
Types of Exploratory Data Analysis (EDA)
Example
use “Titanic Dataset” for EDA
Example Code: https://colab.research.google.com/drive/11JjW055RQ-poNCXTlzPiUxgs9hMi5Xns?usp=sharing
Asking the Right Questions
What type of questions we should ask that gives us a clear picture.
Two types of questions will always be useful for making discoveries with your data
Ex. Understand the distribution and range of key metrics like revenue and engagement.
2. WHAT TYPE OF CO-VARIATION OCCURS BETWEEN MY VARIABLES?
Ex. Explore how different variables interact. For example, does increased engagement lead to higher revenue?
More: Asking the Right Questions
What type of questions we should ask that gives us a clear picture.
Start your analysis with a list of questions, but don’t be afraid to change them!
IDENTIFYING THE KEY VARIABLE OF INTEREST
Generally, there will be one column you care about the most: Revenue, engagement, survival, etc. Focus on how the other variables relate to that.
UNDERSTANDING RELATIONSHIPS, CONSIDERING DEPENDENCIES
You’ll also need your common sense! Think about what columns might be related, what might contribute to what, what might dependent or independent.
Example: Asking the Right Questions
Titanic Dataset
Start your analysis with a list of questions based on your initial hypotheses and domain knowledge.
Refine your questions to gain a deeper understanding of the factors, if needed.
Titanic Dataset
Focus on: you're not only describing the data but also seeking meaningful explanations for observed patterns
EDA Checklist
(NOT PART OF EDA, LATER STAGE): Feature Engineering: Create, modify, or remove features to improve model performance or analysis quality.
If a checklist is essential for pilots on every flight, it’s equally important for data scientists to use with every dataset.
Before Doing EDA… Understand Your Data Structure
EDA is not just plotting. First ask:
Because analysis depends on data structure.
Example Dataset: Cancer Registry
New cancer cases in the U.S. based on a cancer registry.
Some variables describe the person once. Some variables change over time.This is longitudinal data.
What questions can we ask from this data?
Variable Roles in Longitudinal Data
Identifiers
Time-Varying Attributes (Follow-up)
Baseline Attributes (Study Start)
Research Question:
Typical Analysis
Example
distributions, group comparison
trends, change over time
Tracking, grouping
Next: Understanding Variable Types
Continuous Variables (Quantitative) | Categorical Variables (Qualitative) |
Definition: Numeric data that can be rounded or binned into categorical data.
|
|
Before summarizing or visualizing data, identify what type of variable you have.
Categorical variables
Frequency tables - how many observations in each category?
Relative frequency table - percent in each category.
Bar chart and other plots.
Summarizing Variables: Categorical
The goal for both categorical and continuous data is data reduction while preserving/extracting key information about the process under investigation.
Frequency Table: Categories with counts
Relative Frequency Table: Percentage in each category
Graphing a Frequency Table - Bar Chart
Plot the number of observations in each category
Create Frequency Table :
Continuous variables
Summarizing Variables: Continuous
Plot Continuous Data: Age histogram of 10 adult leukemia patients
A histogram is a bar chart showing the frequency of binned data, highlighting how many observations fall into each bin
Create Frequency Table for this new categorical age variable:
Back to Previous Example “Titanic”
We will now start EDA using Pandas!
A Starting Point for Basic Data Manipulation
Once your DataFrame is loaded, first inspect the structure of your data. Some Examples:
scale = {
"strong agree": 2,
"agree": 1,
"neutral": 0,
"disagree": -1,
"strong disagree": -2
}
df["survey_score"] = df["survey_response"].map(scale)
Sometimes a data dictionary explains what each column means ; but often it doesn’t. If unclear, infer meaning from the column name, units, or ask the data provider.
Key idea: Always reshape, recode, or convert data into forms that make analysis clearer and more meaningful.
Learning About Individual Columns (EDA)
df["column"].describe() Provides:
2. Visualize Distribution (Box Plot) Box plots show spread, median, and outliers.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.boxplot(df["column"].values)
plt.show()
count 69.000000 �mean 112.696254 �std 75.825020 �min 23.590017 �25% 69.131239 �50% 95.814021 �75% 143.869780 �max 532.230000 �Name: damage, dtype: float64
Q1 (25th Percentiles)
Q3 (75th Percentiles)
Understanding Distribution of Categorical Variables
To examine how a categorical variable is distributed, use:
df["column"].value_counts()
Example output:
If you want proportions instead of counts:
df["column"].value_counts(normalize=True)
shows:
New Orleans 9 �Seattle 5 �Boston 4 �San Francisco 3 �Long Beach 3 �Memphis 3 �Virginia Beach 3 �Detroit 3 �Dallas 2 �Orlando 2
Understanding Distribution of Continuous Variables
For numeric (continuous) variables, use histograms to visualize how values are distributed.
Ex: df[“column”].hist() will usually work:
Each histogram can tell a different story!�
df["Age"].hist()
df["column"].hist(bins=20)
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Distribution of Column")
plt.show()
Variable Relationships
Visualize how variables are related using plots such as scatter plots or heatmaps; helps reveal patterns, trends, and associations between variables.
Correlation Matrix: To quickly examine relationships between numeric variables: df.corr()
Pearson Correlation (r): Measures strength and direction of a linear relationship.
Range: −1 to 1
Key Idea: Correlation summarizes how strongly two variables move together.
Example: Correlation
df["X"].corr(df["Y"])
Examples: Variable Relationships
Example: You gather a sample of 5,000 college graduates and survey them on their high school SAT scores and college GPAs. You visualize the data to check for a linear pattern:
Scatter Plot = Visualize the Relationship
A scatter plot shows how two numerical variables relate by plotting each observation as a point (shows the relationship pattern between two variables).
df.plot.scatter("col1", "col2")
plt.title("Scatter Plot: Variable Relationship")
plt.show()
Remember: Scatter plot visualizes the relationship (correlation and covariance quantify it.)
Correlation vs Covariance
Covariance → How two variables move together�
Measures joint deviation from the mean.
Example: df["X"].cov(df["Y"])
Interpretation
Advanced: Event Frequency Over a Continuous Variable (e.g., Time)
How often specific events occur across a continuous variable (most commonly time).
Purpose:
Example: Count events by date
df["date"] = pd.to_datetime(df["date"])
df["date"].value_counts().sort_index().plot()
plt.xlabel("Time")
plt.ylabel("Event Count")
plt.title("Events Over Time")
plt.show()
Key Idea: Visualizing event frequency over time helps reveal when activity increases, decreases, or follows recurring patterns.
Advanced: Event Timeline Using a Scatter Plot
How? Create a scatter plot where each dot represents one event along a continuous
variable (e.g., time). Use alpha to make overlapping points transparent so dense areas are easier to see.
df["zeroes"] = 0
df.plot.scatter("days", "zeroes", alpha=0.5)
Purpose:
This is a simple way to visualize when events happen along a continuous scale, especially time.
Sometimes you want to show when events happened, not how many. A simple trick: place all events along a single horizontal line.
Advanced: Checking Seasonal Patterns in Temporal Data
For time-based data, always check for seasonality (yearly, monthly, weekly patterns).
One simple approach is to map time into a repeating cycle and visualize it.
# Calculate day of year (0-364)
df["day_of_year"] = df["days_since_start] % 365
# Create color gradient (red intensity based on day of year)
df["color"] = df["day_of_year"].apply(lambda d: (d/365, 0, 0))
# Plot with colors
df.plot.scatter("day_of_year", "x", c=df["color"])
In this graph, each shade of red corresponds to one specific year.
Idea: If patterns repeat at similar times in the cycle, you likely have seasonality.
Statistical Significance
Identifying Errors
If you have two datasets with different averages, you aren’t allowed to assume they come from different distributions! Oftentimes you’ll need to run a ttest:
stats.ttest_ind(df[x], df[y])
Look for:
Finishing
Once we are done, we should be an expert on our data.
Some Commonly used Pandas syntax patterns for dataframe “df”
Explore by yourself!
Applying Functions
Applying Functions Directly: You can apply functions directly to a DataFrame column:
df[column_name].function()
Applying Custom Functions to a Dataframe Column: df['column_name'].apply(custom_function)
Example: df['frequency'].sum()
# Define a custom function to double a value
Def double_value(value):
return value * 2
# Apply the custom function to the 'values' column and create a new column 'doubled_values'
df['doubled_values'] = df['values'].apply(double_value)
Or use lambda:
df['doubled_values'] = df['values'].apply(lambda x: x**2))
Create a new column in the DataFrame: df['new_col_name']= df['other_column_name'] .apply(custom_function)
In-Place Operations
Perform in-place operations on a column.
# In-place operation
df['column_name'].function(value, inplace=True)
# Non-in-place operation (default behavior)
df_copy = df['column_name'].function (value, inplace=False)
Commonly used syntax patterns for df
Filtering Rows Based on a Condition You can filter rows in a DataFrame based on a condition and then apply statistical functions to a specific column:
df[df['condition']][column_name].statistics_function() df[df['Test_Score'] > 90]['Test_Score'].mean() | |
df[df['column_name'] > value]
boolean_condition
df['Quantity_Kg'] > 5
Q: What about multiple condition?
Grouping and Aggregating Data
You can group data by a condition and calculate statistics within each group:
df.groupby('condition')[column_name].statistics_function()
df.groupby('Category')['Price_USD'].mean()