Exploratory Data Analysis
Exploratory Data Analysis
Exploratory data analysis (EDA) uses summaries and visualizations to understand a dataset and examine relationships among its variables. The appropriate method depends partly on the variable types:
Categorical variables can be explored with frequency tables and two-way tables.
Numerical variables can be compared using scatter plots and correlation measures.
Preparing the data
A data file must be loaded into a suitable data structure before it can be analyzed. In Python, the os library can change the working directory, while the pandas library provides tools for reading and manipulating tabular data. A CSV file can be read into a pandas DataFrame.
import os
import pandas as pd
os.chdir("path/to/data")
cars_data = pd.read_csv(
"Toyota.csv",
index_col=0,
na_values=["?"]
)
cars_data2 = cars_data.copy()Working directory and reading a CSV file
os.chdir(...)changes Python’s working directory to the specified location, allowing the program to access files there.pd.read_csv(...)reads a CSV file and stores its contents as a DataFrame.index_col=0sets the first column in the file as the DataFrame’s index.na_values=["?"]tells pandas to interpret question marks as missing values. This is useful when a file uses a special symbol for missing data, because pandas’ missing-value functions can then be applied to it.
The Toyota dataset contains car attributes such as price, age, distance travelled, fuel type, and gearbox type. In the example, the dataset has 1,436 rows.
Preserving the original data
Before modifying a dataset, a copy can be made with the DataFrame’s .copy() method. The copied DataFrame can be used for analysis while the original remains available for comparison or recovery.
Here, cars_data2 is an independent copy of cars_data. Further operations on cars_data2 therefore do not directly modify the original DataFrame.
Frequency tables for categorical variables
A frequency table reports how many observations belong to each category of a categorical variable. It is useful for univariate analysis: examining one variable at a time to see how its categories are distributed.
Pandas’ crosstab function can produce a frequency table from one variable:
fuel_frequency = pd.crosstab(
index=cars_data2["FuelType"],
dropna=True
)The variable being counted is supplied as the index argument. With dropna=True, records with a missing value for the variable are excluded from this frequency count.
Example: fuel-type frequencies
The Toyota dataset has three observed fuel-type categories:
CNG: 15 cars
Diesel: 144 cars
Petrol: 1,177 cars
The counts total 1,336 non-missing fuel-type records. Compared with the original 1,436 rows, this means 100 records have missing fuel-type values. Petrol is by far the most common observed category in this dataset.
These counts describe this dataset; another sample of cars could have a different distribution.
Two-way tables for categorical variables
A two-way table, also called a cross-tabulation, displays the frequencies for combinations of two categorical variables. It helps examine how the categories of one variable are distributed across the categories of another.
In the Toyota data, the Automatic variable represents gearbox type:
0indicates a manual gearbox.1indicates an automatic gearbox.
The following code places gearbox type in the rows and fuel type in the columns:
gearbox_fuel_frequency = pd.crosstab(
index=cars_data2["Automatic"],
columns=cars_data2["FuelType"],
dropna=True
)Each cell gives the number of records with the row’s gearbox category and the column’s fuel category. For example, a count in the manual–CNG cell represents cars recorded as having both a manual gearbox and CNG fuel.
With missing values excluded, only records with observed values for both variables contribute to the table. The row variable and column variable determine how the output should be read: here, rows correspond to gearbox type and columns correspond to fuel type.
Interpreting the gearbox–fuel table
The observed data show that:
There are 15 manual cars with CNG fuel and 144 manual cars with diesel fuel.
The automatic cars in this table are petrol cars; the automatic–CNG and automatic–diesel cells have counts of zero.
A two-way table shows observed counts, not necessarily a universal rule about cars. The pattern applies to the records in this dataset and could differ in another dataset.
Joint probability from a two-way table
A joint probability is the probability that two events occur together. For two events A and B, it is written as P(A∩B). The events do not need to be independent.
A frequency table can be converted to joint probabilities by dividing each cell count by the total number of included observations. In pandas.crosstab, normalize=True expresses the cell values as proportions of the overall total:
joint_probability = pd.crosstab(
index=cars_data2["Automatic"],
columns=cars_data2["FuelType"],
dropna=True,
normalize=True
)Each cell now represents the proportion of all included records that belong to that row–column combination. For instance, the manual–CNG cell is approximately 0.01, meaning that about 1% of the records included in the table are both manual and CNG.
The manual–petrol joint probability is approximately 0.82. A cell with a value of zero indicates that no records in this dataset have that combination. Because the table contains proportions of the overall total, its cell values sum to 1.
Marginal probability from a two-way table
A marginal probability is the probability of one event without conditioning on the category of the other variable. In a two-way table, marginal probabilities are calculated from the row or column totals divided by the grand total.
The margins=True option adds row totals, column totals, and the overall total. When the table is normalized, these totals are proportions:
marginal_probability = pd.crosstab(
index=cars_data2["Automatic"],
columns=cars_data2["FuelType"],
dropna=True,
normalize=True,
margins=True
)The added totals are labeled All. The row and column totals provide the marginal probabilities:
A row total gives the probability of a gearbox category, regardless of fuel type.
A column total gives the probability of a fuel category, regardless of gearbox type.
The overall total is 1.
For example, the marginal probability of petrol fuel is approximately 0.88. This describes the proportion of included records that have petrol fuel, regardless of whether the gearbox is manual or automatic. The manual-gearbox marginal probability is approximately 0.95, regardless of fuel type.
Conditional probability from a two-way table
A conditional probability is the probability of one event given that another event has occurred. It is expressed as
where P(A∣B) is the probability of A given B. The conditioning event determines the denominator.
In a normalized two-way table:
normalize="index"makes each row sum to 1. The table shows column-category probabilities conditional on each row category.normalize="columns"makes each column sum to 1. The table shows row-category probabilities conditional on each column category.
Fuel type given gearbox type
To find the distribution of fuel types given gearbox type, normalize by row:
fuel_given_gearbox = pd.crosstab(
index=cars_data2["Automatic"],
columns=cars_data2["FuelType"],
dropna=True,
normalize="index"
)Each row sums to 1. For the manual row, the values give the conditional probabilities of CNG, diesel, and petrol among cars with manual gearboxes. In the example data, the probability of petrol among manual cars is approximately 0.87. This is the interpretation of P(petrol∣manual).
For automatic cars, the observed table assigns probability 1 to petrol and 0 to CNG and diesel. This reflects the combinations present in this dataset.
Gearbox type given fuel type
To find gearbox probabilities given fuel type, normalize by column:
gearbox_given_fuel = pd.crosstab(
index=cars_data2["Automatic"],
columns=cars_data2["FuelType"],
dropna=True,
normalize="columns"
)Each column sums to 1. For example, the CNG column shows the probabilities of manual and automatic gearboxes among cars recorded as using CNG. In the observed data, the probability of a manual gearbox given CNG fuel is 1, because no automatic CNG cars appear in the table.
Row-normalized and column-normalized tables answer different questions. The former asks about fuel type given gearbox type; the latter asks about gearbox type given fuel type.
Correlation between numerical variables
Frequency and two-way tables are suited to categorical variables. To examine the association between two numerical variables, analysts can use a scatter plot and a numerical measure called correlation.
Scatter-plot patterns
A positive trend occurs when larger values of one variable tend to appear with larger values of the other. For example, heavier cars might tend to have higher prices.
A negative trend occurs when larger values of one variable tend to appear with smaller values of the other. For example, older cars may tend to have lower prices.
Little or no visible trend occurs when the points do not form a clear increasing or decreasing pattern.
A scatter plot helps reveal the shape and direction of an association. A numerical correlation measure summarizes aspects of that association.
Interpreting correlation values
The Pearson correlation coefficient, commonly written as r, ranges from −1 to 1:
Positive correlation: Values closer to 1 indicate a stronger positive linear association.
Negative correlation: Values closer to −1 indicate a stronger negative linear association.
Zero correlation: A value near 0 indicates little or no linear association.
A value around 0.7 or higher is sometimes treated as a fairly strong correlation, but such thresholds are only rough guidelines. The strength considered meaningful depends on the subject and context. Also, zero correlation does not rule out every possible relationship: variables can have a nonlinear association that Pearson correlation does not capture well.
Correlation describes association, not cause and effect. A strong correlation by itself does not show that changes in one variable cause changes in another.
Calculating correlations in Python
Pandas’ .corr() method calculates pairwise correlations among numerical columns in a DataFrame. By default, it uses the Pearson method and excludes missing values when calculating each pair.
To focus on numerical variables, the example first selects columns whose data types are not object:
numerical_data = cars_data2.select_dtypes(exclude=["object"])
corr_matrix = numerical_data.corr(method="pearson")In the example, this selection produces a DataFrame with 1,436 observations and 8 numerical variables. The .corr() method then calculates the correlation for every pair of numerical columns. The resulting correlation matrix has variable names as both its rows and its columns.
Reading a correlation matrix
The principal diagonal contains values of 1, because each variable is perfectly correlated with itself.
Values above and below the diagonal mirror one another: the correlation of variable X with Y is the same as the correlation of Y with X.
Other cells show the pairwise correlations between distinct variables.
For the Toyota data, the reported relationships include:
Price and age: A correlation of approximately −0.87 indicates a strong negative linear association. Older cars in this dataset tend to have lower prices.
Price and kilometres travelled: A correlation of approximately −0.57 indicates a moderate negative association. Cars that have travelled farther tend to have lower prices.
Price and weight: A correlation of approximately 0.58 indicates a moderate positive association. Heavier cars tend to have higher prices.
Age and kilometres travelled: A correlation near 0.5 indicates a positive association. Older cars tend to have travelled farther.
These interpretations describe trends in the observed data, not rules that apply to every car.
Pearson, Spearman, and Kendall correlations
Pearson correlation measures the strength and direction of a linear association between numerical variables. It is the default method used by .corr() in pandas.
Other correlation measures can be more appropriate for ordinal data or different types of association:
Spearman rank correlation assesses association using the ranks of observations.
Kendall rank correlation also assesses association through ranks and concordance between observations.
The appropriate measure depends on the variables and the question being investigated. In particular, rank-based measures may be used when variables are ordinal rather than measured on a numerical scale.
Key distinctions
A frequency table summarizes the counts for the categories of one categorical variable.
A two-way table summarizes counts for combinations of two categorical variables.
A joint probability describes the probability of a combination of categories.
A marginal probability describes the probability of one category without conditioning on the other variable.
A conditional probability describes the probability of one category given a category of another variable.
Correlation summarizes the direction and strength of association between numerical variables; scatter plots help show the pattern visually.
Together, these methods provide complementary ways to explore categorical and numerical relationships in a dataset.

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