Python Data Analysis
Exploratory Data Analysis with Python and Pandas
Exploratory data analysis (EDA) is the process of becoming familiar with a dataset before performing formal analysis or modeling. It typically involves:
Loading the data.
Understanding its structure and contents.
Preparing and cleaning the data.
Examining individual variables.
Investigating relationships between variables.
Asking and answering meaningful questions with grouped summaries.
The examples use a roller-coaster dataset containing information such as names, locations, manufacturers, materials, heights, speeds, dates, and geographic coordinates.
1. Setting Up the Analysis Environment
A typical Python data-analysis workflow uses several complementary libraries.
Core libraries
Pandas — Provides DataFrame and Series structures for loading, cleaning, transforming, and summarizing tabular data.
NumPy — Supports numerical operations and mathematical data structures.
Matplotlib — Provides general-purpose plotting functionality.
Seaborn — Builds on Matplotlib and provides convenient, statistically oriented visualizations.
Common imports are:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsThe conventional aliases are:
pdfor Pandas.npfor NumPy.pltfor Matplotlib.snsfor Seaborn.
Applying a plotting style
Matplotlib styles can be applied globally:
plt.style.use("ggplot")This gives plots a consistent visual style with grid lines and colors that are often useful during exploration.
Displaying all DataFrame columns
Pandas may hide some columns when a DataFrame is displayed. This is inconvenient when exploring a dataset with many variables. The maximum number of displayed columns can be increased:
pd.set_option("display.max_columns", 200)This changes how DataFrames are displayed; it does not change the underlying data.
2. Loading Data into a DataFrame
A CSV file can be loaded into a Pandas DataFrame with read_csv:
df = pd.read_csv("input/coasterdb.csv")A DataFrame is a two-dimensional table consisting of rows and columns. Each individual column in a DataFrame is a Pandas Series.
The variable df is a common abbreviation for “DataFrame,” although a more descriptive variable name can also be used.
3. Initial Data Understanding
Before cleaning or analyzing a dataset, its basic structure should be examined. This prevents incorrect assumptions about the number of observations, available variables, and data types.
Determining the dataset dimensions
The shape attribute returns the number of rows and columns:
df.shapeFor the roller-coaster dataset, the original data contains:
1,087 rows
56 columns
The result is represented as:
The number of rows represents observations, while the number of columns represents variables or features.
Viewing the first rows
The head method displays the first five rows by default:
df.head()A different number of rows can be requested:
df.head(20)Viewing the first few records helps reveal:
The general format of the data.
Possible inconsistencies.
Whether column values appear sensible.
Whether some variables contain text, numbers, dates, or missing values.
Listing all column names
The columns attribute displays every column name:
df.columnsThis is particularly useful when the dataset contains many variables and helps identify:
Columns that are relevant to the analysis.
Duplicate or redundant measurements.
Poorly named variables.
Columns that should eventually be removed.
Examining data types
The dtypes attribute reports the type assigned to each column:
df.dtypesTypical results include:
object— Commonly used for text or string values.Integer types — Whole-number values such as years or counts.
Floating-point types — Decimal numerical values such as speed, height, or latitude.
Datetime types — Date and time values.
A DataFrame column is a Series, and every Series has a data type. Correct data types are important because they determine which operations can be performed reliably.
Summarizing numerical columns
The describe method produces summary statistics for numerical columns:
df.describe()Important statistics include:
Count — Number of non-missing values.
Mean — Arithmetic average.
Standard deviation — Degree of variation around the mean.
Minimum — Smallest observed value.
25th percentile — Value below which approximately 25% of observations fall.
50th percentile — Median.
75th percentile — Value below which approximately 75% of observations fall.
Maximum — Largest observed value.
For example, the height variable has 171 available values and an average of approximately 101 feet. The difference between the total row count and the count of a particular variable reveals that the variable contains missing data.
Summary statistics provide an initial numerical description of a dataset, but they do not replace visual inspection.
4. Data Preparation and Column Selection
Data preparation involves retaining useful variables, correcting data types, improving names, and investigating data-quality problems.
Columns that will not be used should be removed early. Otherwise, time may be wasted cleaning or transforming variables that are irrelevant to the analysis.
Identifying redundant columns
The dataset contains both:
Text-based columns, such as speed values containing units like “miles per hour.”
Numeric versions of those columns, where text has been removed and values have been standardized.
For example:
A raw speed column may contain strings such as
"50 mph".A cleaned speed column may contain the numeric value 50.
A raw height column may contain units or explanatory text.
A cleaned height column may contain the numeric height in feet.
The numeric versions are generally more useful for calculations and plots.
Selecting a list of columns
A DataFrame can be subsetted by providing a list of desired column names:
df = df[
[
"Coaster Name",
"Location",
"Manufacturer",
"Status",
"Year Introduced",
"Latitude",
"Longitude",
"Material Type",
"Opening Date",
"Speed",
"Height",
"G-force",
"Inversions",
]
].copy()The exact names depend on the dataset, but the process is:
List the columns to retain.
Place the list inside double brackets.
Reassign the result to
df.Use
.copy()to create an independent DataFrame.
Why .copy() matters
When a subset is created, Pandas may return either:
A new independent DataFrame.
A view or reference connected to the original DataFrame.
Using .copy() explicitly creates a separate object:
subset = df[desired_columns].copy()This reduces ambiguity when later modifying values or columns and helps avoid warnings related to chained assignment.
Dropping columns
A column can also be removed with drop:
df = df.drop("Opening Date", axis=1)Several columns can be dropped by passing a list:
df = df.drop(["Status", "Opening Date"], axis=1)The axis argument specifies what is being removed:
axis=0refers to rows.axis=1refers to columns.
Thus, axis=1 is required when dropping columns.
Column selection and column dropping are two alternative strategies:
Selection is useful when the desired columns are known and relatively few.
Dropping is useful when most columns should remain and only a small number need to be removed.
Result of column selection
After selecting the useful variables, the dataset contains:
1,087 rows
13 columns
This smaller DataFrame is easier to inspect and analyze.
5. Correcting Data Types
Correct data types ensure that operations such as sorting, calculating averages, and extracting date components work correctly.
Converting values to dates
If a date column is stored as an object, Pandas is treating it as text rather than as a date. It can be converted with to_datetime:
df["Opening Date"] = pd.to_datetime(df["Opening Date"])After conversion, the column has a datetime data type, commonly displayed as datetime64.
Date conversion enables operations such as:
Sorting chronologically.
Extracting years or months.
Calculating time differences.
Filtering by date ranges.
Creating time-based plots.
Converting values to numeric data
A column can be converted to a numeric type with to_numeric:
df["Year Introduced"] = pd.to_numeric(df["Year Introduced"])This is useful when numbers have been imported as strings. Numeric conversion allows:
Mathematical calculations.
Numeric sorting.
Summary statistics.
Histograms and scatter plots.
If invalid text values are present, pd.to_numeric can also be configured to turn them into missing values using an error-handling option.
Why data types must be checked
A value that looks numeric may still be stored as text. For example, the strings "100" and "20" may sort alphabetically rather than numerically. Likewise, a date stored as text cannot reliably support date-based calculations.
Data cleaning includes not only removing unwanted values but also ensuring that every column has an appropriate representation.
6. Renaming Columns
Clear, consistent column names make code easier to read and reduce errors.
Renaming with a dictionary
Pandas uses a dictionary to map old names to new names:
df = df.rename(
columns={
"coaster_name": "Coaster Name",
"location": "Location",
"manufacturer": "Manufacturer",
}
)Each dictionary entry follows this pattern:
Key: original column name.
Value: replacement column name.
Principles for useful column names
Good column names should be:
Consistent in capitalization.
Descriptive.
Free from unnecessary spaces or confusing abbreviations.
Free from redundant suffixes such as
_cleanwhen the cleaned version is now the only version retained.Easy to reference in code.
For example, consistent names such as Year Introduced, Speed, and Height are easier to interpret than a mixture of lowercase, uppercase, and underscored names.
7. Detecting Missing Values
Missing values occur when an observation does not contain a valid value for a particular variable. They may result from unavailable information, incomplete records, or data-collection limitations.
Identifying missing entries
The isna method returns a Boolean DataFrame:
df.isna()For each cell:
Truemeans the value is missing.Falsemeans the value is present.
Although this reveals where missing values exist, viewing the entire Boolean DataFrame can be overwhelming.
Counting missing values by column
The number of missing values in each column can be calculated by combining isna and sum:
df.isna().sum()Pandas treats True as 1 and False as 0, so summing each column gives its missing-value count.
In the roller-coaster dataset, missing values occur in variables such as:
Status
Latitude
Longitude
G-force
The number of missing values indicates how complete each variable is. A variable with substantial missingness may require special handling before analysis.
Questions to consider about missing data
When missing values are found, analysis should consider:
Is the missingness random or systematic?
Is the variable essential to the planned analysis?
Should rows with missing values be removed?
Should values be imputed?
Does missingness itself convey useful information?
The appropriate response depends on the analytical goal and the reason the values are missing.
8. Detecting Duplicate Rows
Duplicate records can distort counts, averages, and other summaries. Duplicate detection should therefore be performed before analysis.
Finding completely duplicated rows
The duplicated method returns a Boolean Series:
df.duplicated()By default:
The first occurrence of a record is marked
False.Each later identical occurrence is marked
True.
This behavior preserves the first record while identifying additional copies.
Displaying duplicated rows
The duplicated records can be selected with .loc:
df.loc[df.duplicated()]In the dataset, no completely identical rows are found.
Checking duplicates based on selected columns
Rows may not be identical in every column but may still represent the same entity. For example, multiple records can have the same coaster name while differing in another field.
Duplicates can be checked using a subset:
df.duplicated(subset=["Coaster Name"])The duplicate rows can then be displayed:
df.loc[df.duplicated(subset=["Coaster Name"])]This reveals that many coaster names occur more than once.
Investigating suspected duplicates
A specific record can be examined with query:
df.query("`Coaster Name` == 'Crystal Beach Cyclone'")The repeated records may appear almost identical but differ in a field such as Year Introduced. Possible explanations include:
A data-entry error.
A roller coaster being opened, closed, and reopened.
Multiple historical records for the same attraction.
Different versions of an attraction being represented separately.
Duplicate handling must therefore be based on the meaning of the data, not merely on matching text.
Removing duplicates using meaningful identifying columns
If records with the same coaster name, location, and opening date are considered duplicates, those columns can define the duplicate criterion:
duplicate_mask = df.duplicated(
subset=["Coaster Name", "Location", "Opening Date"]
)To retain only the first occurrence, the Boolean mask is inverted with the tilde operator:
df = df.loc[~duplicate_mask]The tilde changes:
TruetoFalse.FalsetoTrue.
Therefore, only records that are not duplicates are retained.
This procedure leaves the first record in each duplicate group and removes subsequent matching records. The result contains:
990 unique roller coasters
13 feature columns
9. Resetting the Index After Removing Rows
When rows are removed, the original index values may contain gaps. For example, the index might progress as:
A continuous index can be restored with reset_index:
df = df.reset_index(drop=True)The drop=True argument prevents the old index from being added as a new column.
Without drop=True, Pandas preserves the old index in a column, which is usually unnecessary after rows have been removed.
Resetting the index does not change the data values; it only creates a new sequential row label.
10. Univariate Analysis
Univariate analysis examines one variable at a time. It is used to understand:
The distribution of values.
Common and uncommon observations.
Central tendencies.
Potential outliers.
Missing or unusual values.
Each individual DataFrame column is a Series, so Series methods can be used directly.
10.1 Value Counts for Discrete Variables
The value_counts method counts the number of times each unique value appears:
df["Year Introduced"].value_counts()By default, the results are ordered from most frequent to least frequent.
For example, the output may show that:
1999 was associated with 46 roller-coaster introductions.
2000 and 1998 were also among the most common years.
Other years occurred less frequently.
This helps identify periods with unusually high or low numbers of observations.
Selecting the most common values
The most frequent values can be selected with head:
df["Year Introduced"].value_counts().head(10)This returns the ten years with the highest counts.
Plotting value counts
Counts can be visualized as a bar chart:
ax = (
df["Year Introduced"]
.value_counts()
.head(10)
.plot(kind="bar", title="Top 10 Years Coasters Were Introduced")
)
ax.set_xlabel("Year Introduced")
ax.set_ylabel("Count")
plt.show()The chart displays:
Years along the horizontal axis.
The number of roller coasters introduced on the vertical axis.
The most common introduction years as bars.
The ax variable stores the Matplotlib axes object, allowing labels and other properties to be added after creating the plot.
Breaking long expressions across lines
A long Python expression can be split across multiple lines inside parentheses. This improves readability without changing the result. In older syntax, backslashes can also be used to continue a line, but parentheses are generally clearer and safer.
10.2 Histograms for Continuous Variables
A histogram shows how frequently numerical values occur within intervals called bins.
For example, speed can be visualized as:
ax = df["Speed"].plot(
kind="hist",
bins=20,
title="Coaster Speed in Miles per Hour"
)
ax.set_xlabel("Speed in Miles per Hour")
plt.show()A histogram is useful for continuous variables such as:
Speed.
Height.
Length.
G-force.
Understanding bins
A bin represents a range of values. The histogram counts how many observations fall within each range.
The number of bins affects interpretation:
Too few bins can hide important structure.
Too many bins can make the plot noisy.
A reasonable bin count can reveal clusters, skewness, gaps, and outliers.
Interpreting a speed histogram
The roller-coaster speed distribution shows:
A concentration of values around approximately 40–50 miles per hour.
A less common set of very high speeds toward the upper end.
Missing values for many older roller coasters.
The extreme values may be potential outliers and should be investigated to determine whether they are valid or erroneous.
10.3 Kernel Density Plots
A kernel density estimate (KDE) plot provides a smoothed estimate of a variable’s distribution.
ax = df["Speed"].plot(
kind="kde",
title="Coaster Speed Density"
)
ax.set_xlabel("Speed in Miles per Hour")
plt.show()A KDE plot:
Produces a smooth curve rather than discrete bars.
Represents the relative concentration of observations.
Makes broad distribution patterns easier to see.
Can be easier to interpret when comparing multiple distributions.
The speed KDE shows prominent concentration around approximately 35 and 50 miles per hour, corresponding to peaks that also appear in the histogram.
Histogram versus KDE
Histogram: Displays actual counts within bins.
KDE plot: Displays a smoothed estimate of the distribution.
Histograms are often easier for understanding counts.
KDE plots are often cleaner for comparing distributions.
Every important feature should be examined individually when performing EDA. Numeric columns can often be explored with histograms or KDE plots, while categorical columns can be examined with value counts and bar charts.
11. Examining Relationships Between Features
After analyzing individual variables, the next step is to investigate how variables relate to one another. This is called bivariate or multivariate analysis, depending on the number of variables involved.
Questions might include:
Do taller roller coasters tend to be faster?
Are newer coasters made from different materials?
Does location relate to coaster speed?
Are certain materials associated with particular heights?
11.1 Scatter Plots
A scatter plot represents each row as a point positioned according to two variables.
For speed and height:
ax = df.plot(
kind="scatter",
x="Speed",
y="Height",
title="Coaster Speed Versus Height"
)
plt.show()The plot uses:
The horizontal axis for speed in miles per hour.
The vertical axis for height in feet.
One point for each roller coaster with available values.
Scatter plots can reveal:
Positive or negative relationships.
Clusters of observations.
Outliers.
Nonlinear patterns.
Regions with few or no observations.
The speed-versus-height plot suggests a positive relationship: taller roller coasters often tend to be faster, although the relationship is not perfect.
Suppressing the raw plotting object
Pandas plotting functions create Matplotlib objects. In some notebook environments, the object representation may be printed in addition to the plot. Calling:
plt.show()displays the plot cleanly.
11.2 Seaborn Scatter Plots
Seaborn provides a more flexible scatter-plot interface:
sns.scatterplot(
x="Speed",
y="Height",
data=df
)
plt.show()The main arguments are:
x— Column used for the horizontal axis.y— Column used for the vertical axis.data— DataFrame containing those columns.
Adding a third variable with hue
A third variable can be represented using color through the hue argument:
sns.scatterplot(
x="Speed",
y="Height",
hue="Year Introduced",
data=df
)
plt.show()This allows the relationship between speed and height to be examined while also considering when each coaster was introduced.
Color encoding can reveal:
Whether newer coasters occupy different regions of the plot.
Whether particular years form clusters.
Whether a relationship changes over time.
Possible historical trends.
11.3 Pair Plots
A pair plot compares multiple variables simultaneously. It produces a matrix in which:
Each off-diagonal cell shows the relationship between a pair of features.
Each diagonal cell shows the distribution of one feature.
A typical pair plot is created with:
sns.pairplot(
df[["Speed", "Height", "Year Introduced", "Inversions"]]
)
plt.show()Pair plots are useful because they combine many univariate and bivariate views in one visualization.
They can reveal:
Correlations between numerical features.
Clusters.
Outliers.
Different distribution shapes.
Variables that appear unrelated.
Possible nonlinear relationships.
Pair plots with hue
A categorical feature can be used to color observations:
sns.pairplot(
df[["Speed", "Height", "Year Introduced", "Inversions", "Material Type"]],
hue="Material Type"
)
plt.show()In the roller-coaster data, colors distinguish material types such as:
Wood.
Steel.
Other materials.
This makes it possible to investigate how construction material relates to other features.
For example, the plot suggests that:
Early roller coasters contain few or no steel examples.
Steel coasters begin appearing more prominently around the 1950s.
Steel becomes increasingly common in later periods.
Pair plots can become visually crowded when too many features or observations are included, so a carefully chosen subset is usually preferable.
12. Correlation Analysis
Correlation measures the strength and direction of a linear relationship between numerical variables.
Calculating correlations
A correlation matrix can be calculated with Pandas:
numeric_df = df[
["Speed", "Height", "Year Introduced", "Inversions", "G-force"]
].dropna()
correlations = numeric_df.corr()The correlation coefficient generally ranges from:
Interpretation:
r=1 — Perfect positive linear relationship.
r=−1 — Perfect negative linear relationship.
r=0 — No linear relationship.
Positive values — Larger values of one feature tend to correspond to larger values of the other.
Negative values — Larger values of one feature tend to correspond to smaller values of the other.
In the dataset, speed and height have a correlation of approximately:
This indicates a fairly strong positive linear relationship.
Important limitations of correlation
Correlation:
Measures linear association, not causation.
May fail to identify nonlinear relationships.
Can be distorted by outliers.
Does not prove that one variable causes another.
Requires careful handling of missing values.
The correlation of every variable with itself is exactly:
Therefore, a correlation matrix always has ones along its main diagonal.
Visualizing correlation with a heat map
Seaborn can display the correlation matrix as a heat map:
sns.heatmap(
correlations,
annot=True
)
plt.show()A heat map uses color intensity to represent correlation strength. The annot=True argument places the numerical correlation values inside the cells.
A heat map makes it easier to identify:
Strong positive relationships.
Strong negative relationships.
Weak or negligible relationships.
Groups of variables that may contain related information.
13. Asking and Answering an Analytical Question
EDA becomes especially useful when it is guided by a specific question.
A meaningful question for the roller-coaster dataset is:
Which locations have the fastest average roller coasters, considering only locations with at least 10 coasters?
This question requires several operations:
Remove invalid or uninformative location values.
Group records by location.
Calculate the average speed at each location.
Count the number of coasters at each location.
Keep only locations with at least 10 coasters.
Sort by average speed.
Visualize the result.
Excluding an uninformative category
The dataset contains an "Other" location category. This does not represent a specific geographic location, so it should be excluded:
location_data = df.query("Location != 'Other'")Filtering prevents an artificial category from being treated as a real location.
Grouping by location
The filtered data can be grouped by location:
grouped = location_data.groupby("Location")Grouping divides the dataset into separate subsets, one for each location.
Aggregating multiple statistics
The agg method can calculate several statistics at once:
location_summary = grouped["Speed"].agg(
["mean", "count"]
)For each location, this produces:
Mean speed — Average coaster speed.
Count — Number of non-missing speed observations.
The result has one row per location.
A named aggregation can make the output clearer:
location_summary = (
location_data.groupby("Location")
.agg(
Mean_Speed=("Speed", "mean"),
Coaster_Count=("Speed", "count")
)
)Filtering by a minimum group size
To keep only locations with at least 10 coasters:
location_summary = location_summary.query(
"Coaster_Count >= 10"
)This minimum-count requirement is important because an average based on only one or two coasters may be unstable and misleading.
Sorting the results
The locations can be ordered by average speed:
location_summary = location_summary.sort_values(
"Mean_Speed"
)Sorting allows the fastest and slowest qualifying locations to be identified easily.
Visualizing the results
A horizontal bar plot is appropriate for comparing locations:
ax = location_summary["Mean_Speed"].plot(
kind="barh",
title="Average Coaster Speed by Location"
)
ax.set_xlabel("Average Coaster Speed")
plt.show()A horizontal plot is particularly useful when location names are long because the labels are easier to read.
Interpretation
The analysis shows that:
Busch Gardens has the highest average coaster speed among locations with at least 10 coasters.
Cedar Point follows.
Other qualifying locations appear below them according to their calculated average speed.
The conclusion applies only to locations meeting the minimum threshold and only to the available non-missing speed values.
14. General EDA Workflow
A practical workflow for exploring a new dataset is:
Import analysis libraries.
Load Pandas, NumPy, Matplotlib, and Seaborn.
Set useful display and plotting options.
Load the dataset.
Read the source file into a DataFrame.
Inspect its structure.
Check
shape.View
head.List
columns.Inspect
dtypes.Run
describe.
Prepare the variables.
Retain only relevant columns.
Remove redundant or unused variables.
Use
.copy()when creating a working subset.
Correct data types.
Convert dates with
pd.to_datetime.Convert numeric-looking text with
pd.to_numeric.
Standardize column names.
Use consistent capitalization and naming conventions.
Remove unnecessary suffixes or confusing formatting.
Check data quality.
Count missing values with
df.isna().sum().Search for duplicate rows.
Investigate duplicates using meaningful identifying columns.
Remove duplicates when justified.
Reset the index after deleting rows.
Perform univariate analysis.
Use
value_countsfor categorical or discrete variables.Use histograms for continuous variables.
Use KDE plots for smoothed distributions.
Perform relationship analysis.
Use scatter plots for pairs of numerical features.
Use
hueto incorporate a third variable.Use pair plots for multiple feature comparisons.
Use correlation matrices and heat maps for numerical relationships.
Ask a focused question.
Filter irrelevant records.
Group observations.
Aggregate meaningful statistics.
Apply thresholds.
Sort and visualize the results.
Effective EDA combines structural inspection, data cleaning, visualization, statistical summaries, and question-driven analysis.
The most valuable skill is not memorizing isolated Pandas commands but learning how to combine them to answer meaningful questions about unfamiliar data.

Ask anything
We've read this whole study set, so questions about it get the best answers.