Exploratory Data Analysis with Python
Exploratory data analysis became useful when it exposed the assumptions hidden in a nutritional dataset—not when it produced another chart or summary table.
Part of the Python and Data Science for .NET Developers series
Phase Practice, Part 5
Data Science Series — 6 articles
Filed under Pragmatic architecture and modernization
Topic cluster
Python and Data SciencePython, data analysis, visualization, and machine learning foundations from a .NET developer's perspective.
The Dataset Looked Clean Until I Asked Better Questions
The nutritional dataset I used in the UT Austin AI/ML program arrived in a familiar shape: rows of foods, columns of nutrients, and enough numeric values to make modeling feel like the obvious next step. It loaded into a pandas DataFrame without complaint. Nothing about it looked broken.
That was precisely the risk.
A dataset does not need malformed CSV or missing headers to mislead an analysis. A zero may mean “none,” “not measured,” or “unknown.” Two food names may describe the same product at different serving sizes. A nutrient measured in milligrams can dominate a feature expressed in grams once the values reach a distance-based model. The file can be syntactically valid while the assumptions underneath it remain unsettled.
Exploratory data analysis became useful here because it slowed down the rush toward modeling. The goal was not to produce every available chart. It was to identify which decisions I would otherwise make silently.
Start With the Shape, Then Challenge the Meaning
I worked in Google Colab with pandas, Matplotlib, and seaborn. The dataset included food descriptions and nutritional features such as protein, fat, vitamin C, and fiber. The full notebook and supporting files are available in my Google Drive folder.
My first pass was deliberately plain:
df.shape
df.head()
df.info()
df.describe(include="all").transpose()
df.isna().sum().sort_values(ascending=False)
df.duplicated().sum()These commands answer different questions. shape and head confirm that I loaded what I expected. info exposes types and nullability. describe makes improbable ranges visible. Missing-value and duplicate counts identify where absence or repetition might alter the analysis.
The commands are simple; interpreting them is not. A duplicate row could be accidental, or it could represent two legitimate products with identical measured nutrients. A zero vitamin value could be real, or it could be the dataset's substitute for an unavailable measurement. Removing or imputing either one without checking the data dictionary would turn uncertainty into a fact.
Missing Values Are Domain Decisions
The usual menu for missing data is short: remove the row, fill the value, or preserve the absence as a signal. None of those choices is universally correct.
In nutritional data, replacing a missing nutrient with zero is especially tempting and especially dangerous. Zero states that the food contains none of that nutrient. Missing states that the dataset does not tell me. A model cannot recover that distinction after I erase it.
I started by making the missingness visible alongside the affected records:
missing_counts = df.isna().sum()
missing_columns = missing_counts[missing_counts > 0].index
for column in missing_columns:
display(df.loc[df[column].isna(), ["food_name", column]].head())That inspection changed the question from “How do I fill nulls?” to “Why is this feature missing for these foods?” Sometimes the answer supports imputation. Sometimes it supports dropping a feature. Sometimes the absence itself deserves a separate indicator. The important part is that the choice becomes explicit before it influences every later result.
Distributions Expose What Averages Hide
Summary statistics gave me a useful inventory, but nutrient features were heavily skewed. A small number of foods carried values far beyond the median, and those values pulled means away from what a typical row looked like.
I used the same compact routine across numerical columns to compare the distribution, center, and potential outliers:
def inspect_numeric_features(df, features):
for feature in features:
skewness = df[feature].skew()
minimum = df[feature].min()
maximum = df[feature].max()
mean = df[feature].mean()
mode = df[feature].mode().values[0]
unique_count = df[feature].nunique()
variance = df[feature].var()
std_dev = df[feature].std()
percentile_25 = df[feature].quantile(0.25)
median = df[feature].median()
percentile_75 = df[feature].quantile(0.75)
data_range = maximum - minimum
print({
"feature": feature,
"skewness": round(skewness, 4),
"min": minimum,
"max": maximum,
"mean": round(mean, 4),
"mode": mode,
"unique_count": unique_count,
"variance": round(variance, 4),
"std_dev": round(std_dev, 4),
"p25": percentile_25,
"median": median,
"p75": percentile_75,
"range": data_range,
})
plt.figure(figsize=(18, 6))
plt.subplot(1, 3, 1)
sns.kdeplot(df[feature], fill=True)
plt.title(f"KDE of {feature}")
plt.subplot(1, 3, 2)
sns.boxplot(df[feature])
plt.title(f"Box Plot of {feature}")
plt.subplot(1, 3, 3)
sns.histplot(df[feature], bins=10, kde=True)
plt.title(f"Histogram of {feature}")
plt.tight_layout()
plt.show()The three views serve different purposes. The histogram shows where most values sit. The KDE makes the distribution's shape easier to compare across features. The box plot makes extreme observations difficult to ignore.
An outlier is not automatically bad data. In this dataset, a high nutrient value might be a unit error, a fortified product, or a genuinely unusual food. I treated the chart as a queue for investigation rather than permission to delete points.
Relationships Need a Question
It is easy to generate a correlation heatmap across every numeric feature. It is harder to decide which relationships matter.
For the nutritional analysis, I was preparing for a clustering experiment. That made scale, redundancy, and feature dependence more important than a generic search for strong correlations. If two columns carried nearly the same signal, including both could give that concept extra influence. If one feature had a much larger numeric range, it could dominate Euclidean distance even when it was not more important.
numeric = df.select_dtypes(include="number")
correlations = numeric.corr()
plt.figure(figsize=(12, 9))
sns.heatmap(correlations, cmap="coolwarm", center=0)
plt.title("Nutrient Feature Correlations")
plt.tight_layout()
plt.show()The heatmap did not tell me which features to keep. It showed where I needed to make and document a choice. That distinction matters: visualization supports judgment; it does not replace it.
Automation Should Preserve Curiosity
Reusable inspection functions made the notebook faster and more consistent, but there is a trap in automating EDA. A function that emits thirty charts can create the appearance of thoroughness while making it easier to skim past the one chart that challenges the model design.
I found the better balance was to automate repetitive calculation and layout, then pause at each suspicious distribution or relationship. The notebook remained reproducible without turning exploration into a report generator.
This also changed how I thought about the next phase. Before EDA, K-means looked like a straightforward algorithm choice. After EDA, the important modeling questions were more concrete: Which features should be scaled? Which missing values could be defended? Were the apparent clusters driven by nutrition or by measurement units?
Those questions led directly to Exploring Nutritional Data with K-means Clustering. The clustering article begins where this one ends—not with a perfectly clean dataset, but with a documented set of decisions and uncertainties.
EDA is often described as a preliminary step. In practice, I keep returning to it whenever a model produces a surprising result. The charts and statistics are useful, but the real product is a better account of what I believe about the data and why. A model built after that work may still be wrong. At least its assumptions are visible enough to challenge.
Automating Univariate and Bivariate Analysis in Python
During your Data Sanity checks, it's essential to classify your variables into numerical, categorical, and dependent types before starting your Exploratory Data Analysis (EDA).
In the early stages of data analysis, you will often need to determine whether your variables are numerical, categorical, or dependent. Identifying these is crucial for:
- Performing the correct statistical methods on your data
- Automating your exploratory analysis using scripts
- Generating meaningful insights into relationships between features
Once these variables are classified, you can begin the process of performing univariate (analyzing one variable) and bivariate (analyzing relationships between two variables) analysis. Automating this process will save you time and ensure consistency in your Exploratory Data Analysis (EDA).
Automating Univariate Analysis for Numerical and Categorical Features
In univariate analysis, you focus on understanding the distribution of a single feature. The following Python functions allow you to automate this process for both numerical and categorical features.
This function calculates the key statistical attributes for a numerical feature, including mean, median, variance, and skewness. It also provides visual insights using KDE plots, BoxPlots, and Histograms.
Here's the full implementation of the function:
def univariate_analysis(df, features):
for feature in features:
skewness = df[feature].skew()
minimum = df[feature].min()
maximum = df[feature].max()
mean = df[feature].mean()
mode = df[feature].mode().values[0]
unique_count = df[feature].nunique()
variance = df[feature].var()
std_dev = df[feature].std()
percentile_25 = df[feature].quantile(0.25)
median = df[feature].median()
percentile_75 = df[feature].quantile(0.75)
data_range = maximum - minimum
print(f"Univariate Analysis for {feature}")
print(f"Skewness: {skewness:.4f}")
print(f"Min: {minimum}")
print(f"Max: {maximum}")
print(f"Mean: {mean:.4f}")
print(f"Mode: {mode}")
print(f"Unique Count: {unique_count}")
print(f"Variance: {variance:.4f}")
print(f"Std Dev: {std_dev:.4f}")
print(f"25th Percentile: {percentile_25}")
print(f"Median (50th Pct): {median}")
print(f"75th Percentile: {percentile_75}")
print(f"Range: {data_range}")
plt.figure(figsize=(18, 6))
plt.subplot(1, 3, 1)
sns.kdeplot(df[feature], fill=True)
plt.title(f"KDE of {feature}")
plt.subplot(1, 3, 2)
sns.boxplot(df[feature])
plt.title(f"Box Plot of {feature}")
plt.subplot(1, 3, 3)
sns.histplot(df[feature], bins=10, kde=True)
plt.title(f"Histogram of {feature}")
plt.tight_layout()
plt.show()This function provides a comprehensive analysis for each numerical feature by calculating statistical attributes and generating KDE, BoxPlot, and Histogram visualizations.
Categorical Univariate Analysis
For categorical features, we analyze the distribution of categories and their relationship with the dependent feature. Here's a function that automates this process:
def univariate_analysis_categorical(df, categorical_features):
for feature in categorical_features:
unique_categories = df[feature].nunique()
mode = df[feature].mode().values[0]
mode_freq = df[feature].value_counts().max()
category_counts = df[feature].value_counts()
category_percent = df[feature].value_counts(normalize=True) * 100
missing_values = df[feature].isnull().sum()
total_values = len(df[feature])
imbalance_ratio = category_counts.max() / total_values
print(f"Univariate Analysis for {feature}")
print(f"Unique Categories: {unique_categories}")
print(f"Mode (Most frequent): {mode}")
print(f"Frequency of Mode: {mode_freq}")
print(f"Missing Values: {missing_values}")
print(f"Imbalance Ratio (Max/Total): {imbalance_ratio:.4f}")
print(f"Category Counts:\n{category_counts}")
plt.figure(figsize=(10, 6))
sns.countplot(x=df[feature], order=df[feature].value_counts().index)
plt.title(f"Frequency of {feature} Categories")
plt.xlabel(feature)
plt.ylabel("Count")
plt.tight_layout()
plt.show()This function provides a clear understanding of how categories are distributed across the data and helps identify potential imbalances.
Automating Bivariate Analysis
Bivariate analysis allows you to understand the relationship between two variables. Here's how you can automate this process.
The following function calculates key attributes for a numerical feature in relation to a boolean dependent feature. It prints out key insights and generates side-by-side visualizations to understand their relationship.
def bivariate_analysis(df, numerical_features, categorical_features, dependent_feature):
if numerical_features:
for feature in numerical_features:
mean_0 = df[df[dependent_feature] == 0][feature].mean()
mean_1 = df[df[dependent_feature] == 1][feature].mean()
median_0 = df[df[dependent_feature] == 0][feature].median()
median_1 = df[df[dependent_feature] == 1][feature].median()
var_0 = df[df[dependent_feature] == 0][feature].var()
var_1 = df[df[dependent_feature] == 1][feature].var()
print(f"Mean {feature} for group 0: {mean_0:.2f}")
print(f"Mean {feature} for group 1: {mean_1:.2f}")
print(f"Median {feature} for group 0: {median_0:.2f}")
print(f"Median {feature} for group 1: {median_1:.2f}")
print(f"Variance of {feature} for group 0: {var_0:.2f}")
print(f"Variance of {feature} for group 1: {var_1:.2f}")
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
sns.boxplot(x=df[dependent_feature], y=df[feature], ax=axes[0])
axes[0].set_title(f"{feature} Distribution by {dependent_feature}")
sns.barplot(x=df[dependent_feature], y=df[feature], estimator='mean', ax=axes[1])
axes[1].set_title(f"Mean {feature} by {dependent_feature}")
plt.tight_layout()
plt.show()
if categorical_features:
for feature in categorical_features:
category_distribution = df.groupby([feature, dependent_feature]).size().unstack(fill_value=0)
chi2, p, dof, expected = chi2_contingency(category_distribution)
print(f"Chi-Square Test for {feature}: Chi2 = {chi2:.4f}, p-value = {p:.4f}")
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
sns.countplot(x=df[feature], hue=df[dependent_feature], ax=axes[0])
axes[0].set_title(f"{feature} Count by {dependent_feature}")
sns.barplot(x=df[feature], y=df[dependent_feature], estimator='mean', ax=axes[1])
axes[1].set_title(f"Proportion of {dependent_feature} by {feature}")
plt.tight_layout()
plt.show()This function performs bivariate analysis by calculating key attributes and generating box plots, bar plots, and count plots to help you better understand the relationship between variables.
EDA FAQ
What is Exploratory Data Analysis (EDA)?
EDA is the process of analyzing datasets to summarize their main characteristics, often using visual methods.
Why is EDA important?
EDA helps you understand your data, detect anomalies, test assumptions, and prepare for modeling.
What are common EDA techniques?
Common techniques include summary statistics, visualizations (histograms, boxplots, scatter plots), and correlation analysis.
How do I handle missing data in EDA?
Identify missing values, then decide whether to remove, impute, or flag them based on context.
What Python libraries are best for EDA?
pandas, matplotlib, seaborn, and missingno are popular libraries for EDA in Python.
Summary Checklist
- Data sanity checks and EDA steps explained
- Code samples use PrismJS markup
- SEO and accessibility best practices followed
- Table of Contents, FAQ, and Glossary included
- Bootstrap 5 and icons used for layout and navigation
Glossary of Terms
EDA (Exploratory Data Analysis)
Exploratory Data Analysis (EDA) is the process of analyzing datasets to summarize their main characteristics, often using visual methods.
For more, see the Wikipedia article on EDA.
Outlier
An outlier is a data point that differs significantly from other observations in a dataset.
Learn more at Wikipedia: Outlier.
IQR (Interquartile Range)
The interquartile range (IQR) is a measure of statistical dispersion, being equal to the difference between the upper and lower quartiles.
See Wikipedia: Interquartile range for details.
Skewness
Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable about its mean.
More info: Wikipedia: Skewness.
Pandas
Pandas is a powerful open-source Python library for data manipulation and analysis, providing flexible data structures like DataFrames.
See Wikipedia: Pandas (software).
Explore More
- When the First Visualization Answers the Wrong Question -- Why choosing a chart is part of the analysis
- Python: The Language of Data Science -- Understanding Python's Impact on Data Science
- Data Science for .NET Developers -- Why .NET Developers Should Consider Data Science
- Exploring Nutritional Data Using K-means Clustering -- Unveiling Patterns in Nutritional Data
- Understanding Neural Networks -- A Beginner's Guide to Neural Networks
Related project evidence

Frogsfolly.com Main
Frogsfolly.com is the original website I created in 1999 when learning web technologies.
GitHub Stats Spark
Automated GitHub profile statistics generator with AI-powered repository analysis, SVG visualizations, and the pipeline that feeds live repository data to this site.
Powers the repository stats on this site
Working through something similar?
If this maps to something you're working on, I'm glad to compare notes. Start with the system and the constraint that matters most.