Statistics for data analysis is the set of tools you use to summarize data (averages and spread), find unusual values, measure relationships between variables, and decide whether a difference you see is real or just random noise.
You do not need a math degree to use statistics well. A data analyst needs a handful of ideas and the judgment to know when each one applies: use the median instead of the mean when a few huge values distort the average, check for outliers before trusting a result, and never confuse correlation with causation. This guide covers those ideas in the order you will meet them in real work, with short Python examples you can run yourself, and with the matching Excel and SQL functions at the end. If you are new to the field, start with what a data analyst does.
Descriptive vs. Inferential Statistics
Statistics has two main jobs:
- Descriptive statistics summarize the data you have: the average order value, the spread of delivery times, the most common product.
- Inferential statistics use a sample to draw conclusions about a larger group: “Did the new checkout page increase conversions, or was that luck?”
Most day-to-day analysis is descriptive. Inference comes in when you have to make a decision under uncertainty, such as an A/B test or a survey.
Set Up Python
The examples use pandas for data tables and scipy for statistical tests. If you do not have them yet:
pip install pandas scipy
They work well in a Jupyter Notebook. For more on loading and cleaning data first, see Python for data analysis and cleaning data with pandas.
Know Your Data Types
The kind of data decides which statistics make sense.
| Type | Examples | Sensible statistics |
|---|---|---|
| Numeric, continuous | Price, weight, time | Mean, median, standard deviation, correlation |
| Numeric, discrete | Number of orders, number of children | Counts, mean, median |
| Categorical, nominal | Country, product category, channel | Counts, percentages, mode |
| Categorical, ordinal | Rating (poor to excellent), education level | Median, mode, counts |
An average of “country” makes no sense, and an average of numbers that are really category codes (1 = email, 2 = ads) is meaningless too.
Measures of Center: Mean, Median, and Mode
Suppose these are the values of twelve orders, in dollars. One customer placed a very large order:
import pandas as pd
order_values = pd.Series([42, 38, 45, 40, 44, 39, 41, 43, 37, 46, 40, 250])
print(order_values.mean()) # 58.75
print(order_values.median()) # 41.5
print(order_values.mode().tolist()) # [40]
- The mean is the sum divided by the count. It uses every value, so it is pulled strongly by extremes.
- The median is the middle value when the data is sorted. Half the values are below it and half above. It barely moves when one value is extreme.
- The mode is the most frequent value, most useful for categories and discrete counts.
Here, the mean is 58.75, yet eleven of the twelve orders are between 37 and 46. The single 250 order drags the mean far above what is typical. The median, 41.5, describes a typical order much better.
Rule of thumb: if the mean and median are close, the data is roughly balanced. If the mean is much larger than the median, a few large values are pulling it up (right skew), and the median is usually the better summary. Income, house prices, and website session lengths often behave like this.
Measures of Spread: How Much Do Values Vary?
Two groups can have the same average and very different consistency, so the center is never enough.
- Range: the maximum minus the minimum. Simple but sensitive to extremes.
- Variance and standard deviation: how far values typically sit from the mean. The standard deviation is in the same units as the data, so it is easier to read.
- Percentiles and quartiles: the value below which a given percent of the data falls. The 25th, 50th, and 75th percentiles are the quartiles.
- Interquartile range (IQR): the 75th percentile minus the 25th. It describes the middle half of the data and ignores the extremes.
print(order_values.describe().round(2))
count 12.00
mean 58.75
std 60.29
min 37.00
25% 39.75
50% 41.50
75% 44.25
max 250.00
dtype: float64
describe() is usually your first command on a new column. A standard deviation of 60.29 on a mean of 58.75 tells you right away that the data varies enormously, which is a hint that something unusual is in there.
Note that pandas uses the sample standard deviation (dividing by n − 1) by default, which is what you want when your data is a sample of a larger population. NumPy’s np.std defaults to the population version (dividing by n), so the two can differ slightly for small datasets. Check which one your tool uses.
Finding Outliers
An outlier is a value far from the rest. It may be an error (a typo, a broken sensor, a duplicate), or a real but rare event (a wholesale order). Either way, you need to find it before you trust any average.
The IQR Rule
A common rule flags values more than 1.5 × IQR below the first quartile or above the third:
q1, q3 = order_values.quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(low, high) # 33.0 51.0
print(order_values[(order_values < low) | (order_values > high)].tolist()) # [250]
The Z-Score
A z-score says how many standard deviations a value is from the mean:
z = (order_values - order_values.mean()) / order_values.std()
print(z.iloc[-1].round(2)) # 3.17
A common rough cutoff is an absolute z-score above 3. But notice the weakness: the outlier itself inflates the mean and standard deviation, so it looks less extreme than it really is. The IQR rule is more robust for small or skewed data.
What to Do With Outliers
Do not delete a value just because it is unusual. Ask:
- Is it an error? If yes, fix or remove it.
- Is it real but rare? Keep it, but report results with and without it.
- Does it matter for the question? If you are forecasting typical demand, a one-time bulk order may not belong. If you are looking at fraud, it is the whole point.
Removing the 250 here changes the story:
without = order_values[order_values < 100]
print(without.mean().round(2), without.median(), without.std().round(2))
# 41.36 41.0 2.91
The mean drops from 58.75 to 41.36 and the standard deviation from 60.29 to 2.91. Always document what you removed and why.
Distributions and Skewness
A distribution describes how values are spread across their range. Plotting a histogram is the fastest way to see it (see data visualization with Python). Two things to look for:
- Skewness: a long tail to one side. A skew near 0 means symmetric. A large positive value means a long right tail.
- Shape: one peak, two peaks (often two groups mixed together), or flat.
print(order_values.skew().round(2)) # 3.45
print(without.skew().round(2)) # 0.16
The outlier makes the data heavily right-skewed (3.45). Without it, the data is nearly symmetric (0.16).
The Normal Distribution
Many measurements, such as heights and measurement errors, follow a bell-shaped normal distribution. For roughly normal data, about 68% of values fall within one standard deviation of the mean, about 95% within two, and about 99.7% within three. You can check this with simulated data:
import numpy as np
rng = np.random.default_rng(42)
sample = rng.normal(100, 15, 1000)
within_one_sd = ((sample > 85) & (sample < 115)).mean()
print(round(within_one_sd, 3)) # 0.688
About 69% of the simulated values are within one standard deviation of 100, close to the expected 68%. Many real datasets, such as incomes and wait times, are not normal, so check the shape before relying on normal-distribution rules.
Comparing Groups
Often the question is “how do these groups differ?” groupby gives the summary for each group:
df = pd.DataFrame({
'channel': ['email'] * 6 + ['ads'] * 6,
'order_value': [52, 48, 55, 50, 47, 53, 44, 41, 46, 43, 45, 42],
'ad_spend': [10, 12, 15, 11, 9, 14, 30, 28, 35, 31, 29, 33],
})
print(df.groupby('channel')['order_value'].agg(['count', 'mean', 'median', 'std']).round(2))
count mean median std
channel
ads 6 43.50 43.5 1.87
email 6 50.83 51.0 3.06
Orders from email average about 50.83 and orders from ads about 43.50. Whether that difference is real or random is a question for a hypothesis test, covered below.
Correlation: Do Two Variables Move Together?
Correlation measures how strongly two numeric variables move together, on a scale from −1 to +1. Near +1, they rise together. Near −1, one rises as the other falls. Near 0, there is no linear relationship.
from scipy import stats
r, p = stats.pearsonr(df['ad_spend'], df['order_value'])
print(round(r, 3), round(p, 5)) # -0.749 0.00503
The correlation between ad spend and order value is -0.749, a fairly strong negative relationship. But look at why. In this data, the “ads” rows have both higher spend and lower order value, so the correlation is really picking up the channel difference, not a direct effect of spending. That is a classic trap.
Correlation does not mean causation. Three things can produce a correlation without one variable causing the other: coincidence, a third variable driving both (a confounder, like channel here), or reverse causation. To establish cause, you generally need an experiment (such as an A/B test) or careful causal analysis.
Also remember that Pearson correlation only captures straight-line relationships. Always plot the two variables, since a strong curved pattern can have a correlation near zero.
Linear Regression: Fitting a Line
Simple linear regression fits a straight line to predict one variable from another. Suppose monthly ad spend (in thousands) and revenue (in thousands) look like this:
spend = [10, 15, 20, 25, 30, 35, 40, 45]
revenue = [120, 150, 170, 210, 230, 270, 290, 330]
res = stats.linregress(spend, revenue)
print(round(res.slope, 3), round(res.intercept, 3), round(res.rvalue ** 2, 4))
# 5.929 58.214 0.9951
- The slope (
5.929) says that each extra unit of spend is associated with about 5.9 more units of revenue. - The intercept (
58.214) is the predicted revenue at zero spend. - R² (
0.9951) is the share of the variation in revenue explained by the line. Here, about 99.5%.
You can predict with the line:
print(round(res.intercept + res.slope * 40, 1)) # 295.4
A word of caution. This data is unusually clean, so the fit is excellent. Real data is noisier, and a high R² does not prove causation. Also avoid extrapolating: predicting for a spend of 100 when you only observed 10 to 45 assumes the same straight-line pattern continues, which may not be true. Predictions inside the observed range are far more trustworthy.
Samples, Populations, and Confidence Intervals
Usually you cannot measure everyone, so you take a sample and use it to estimate the population. A sample mean is an estimate, and a confidence interval shows how uncertain it is.
ci_low, ci_high = stats.t.interval(0.95, len(without) - 1,
loc=without.mean(), scale=stats.sem(without))
print(round(without.mean(), 2), round(float(ci_low), 2), round(float(ci_high), 2))
# 41.36 39.41 43.32
The sample mean is 41.36, and a 95% confidence interval runs from about 39.41 to 43.32. Loosely speaking, if you repeated the sampling many times and built an interval each time, about 95% of those intervals would contain the true population mean. It is not a statement that there is a 95% probability the true mean lies in this one interval, which is a common misreading.
Two practical points:
- Bigger samples give narrower intervals. More data means a more precise estimate.
- Samples must be representative. A large but biased sample (for example, only customers who answered a survey) can mislead you more than a small random one.
Hypothesis Testing: Is the Difference Real?
A hypothesis test asks whether the pattern in your sample could plausibly be due to chance.
- State a null hypothesis: there is no difference (or no effect).
- Compute a test statistic and its p-value.
- The p-value is the probability of seeing a result at least this extreme if the null hypothesis were true.
- If the p-value is below a threshold you chose beforehand (often 0.05), you call the result statistically significant and reject the null.
Comparing Two Averages: The t-Test
Is the difference between email and ads order values real?
email = df[df.channel == 'email']['order_value']
ads = df[df.channel == 'ads']['order_value']
t, p = stats.ttest_ind(email, ads, equal_var=False)
print(round(t, 3), round(p, 5)) # 5.008 0.00094
The p-value is about 0.0009, well under 0.05, so the difference between channels is unlikely to be random. The equal_var=False option is Welch’s t-test, which does not assume both groups have the same variance and is a safe default.
Comparing Two Rates: The Chi-Square Test
For conversion rates in an A/B test, suppose version A converted 30 of 300 visitors and version B converted 50 of 300:
import numpy as np
table = np.array([[30, 270],
[50, 250]]) # [converted, did not convert] for A and B
chi2, p, dof, expected = stats.chi2_contingency(table)
print(round(chi2, 3), round(p, 4)) # 5.207 0.0225
The p-value is about 0.0225, so a difference between a 10% and a 16.7% conversion rate at this sample size is unlikely to be chance. SciPy applies a continuity correction to a 2×2 table by default, which is why the statistic is 5.207 rather than 5.769 without it.
What a p-Value Does Not Tell You
- It is not the probability that the null hypothesis is true.
- A small p-value does not mean the effect is large or important. With a huge sample, a trivial difference can be “significant”. Look at the effect size (the actual difference) and ask whether it matters in practice.
- A large p-value does not prove there is no effect. You may just not have enough data.
- Running many tests and reporting only the significant ones (sometimes called p-hacking) produces false findings. Decide the question and the threshold before you look at the data, and be cautious when testing many things at once.
Common Mistakes to Avoid
- Reporting only the mean. Always look at the median and the spread too.
- Ignoring outliers or deleting them without a reason.
- Confusing correlation with causation.
- Skipping the chart. Plot the data before and after the numbers.
- Treating “not significant” as “no effect”.
- Using a small or biased sample and generalizing from it.
- Extrapolating a model far outside the observed range.
- Mixing up sample and population formulas, such as the n versus n − 1 standard deviation.
- Testing many hypotheses and highlighting only the hits.
- Forgetting the units and the context. A statistic with no business meaning is just a number.
The Same Ideas in Excel and SQL
You do not need Python for every analysis. These are the matching functions:
| Idea | Excel | SQL (PostgreSQL syntax) | pandas |
|---|---|---|---|
| Mean | AVERAGE | AVG(x) | .mean() |
| Median | MEDIAN | PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) | .median() |
| Standard deviation (sample) | STDEV.S | STDDEV_SAMP(x) | .std() |
| Variance (sample) | VAR.S | VAR_SAMP(x) | .var() |
| Quartiles | QUARTILE.INC | PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY x) | .quantile(0.25) |
| Correlation | CORREL | CORR(y, x) | .corr() |
| Regression slope | SLOPE | REGR_SLOPE(y, x) | scipy.stats.linregress |
| t-test | T.TEST | (usually done in Python or R) | scipy.stats.ttest_ind |
For example, in SQL, the summary of the order values might look like this:
SELECT
AVG(order_value) AS mean_value,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY order_value) AS median_value,
STDDEV_SAMP(order_value) AS std_value
FROM orders;
See SQL aggregate functions for the basics, and Excel for data analysis for the spreadsheet route. For fast array math behind many of these calculations, see the NumPy guide.
A Four-Week Learning Plan
- Week 1: Descriptive statistics. Run
describe()on three real datasets and compare the mean and median. - Week 2: Spread and outliers. Find outliers with the IQR rule, and decide what to do with each.
- Week 3: Relationships. Compute correlations, plot scatter charts, and fit a simple regression.
- Week 4: Inference. Build confidence intervals and run a t-test and a chi-square test on a real A/B comparison.
Practice with data you care about, such as your own spending, sports results, or a public dataset. Statistics sticks when you apply it to a question you want answered.
Frequently Asked Questions
What statistics should a data analyst know?
At minimum: mean, median, mode, standard deviation, percentiles, outlier detection, correlation, simple regression, confidence intervals, and basic hypothesis tests (t-test and chi-square). Add probability, sampling, and A/B testing as you advance.
When should I use the median instead of the mean?
Use the median when the data is skewed or has outliers, such as incomes, prices, or time on site. Report both when you can, since a large gap between them tells you the data is skewed.
What does a p-value of 0.05 mean?
It means that if there were truly no effect, you would see a result at least this extreme about 5% of the time. It is a convention, not a law, and it says nothing about how large or important the effect is.
What is the difference between correlation and causation?
Correlation means two variables move together. Causation means one produces a change in the other. A correlation can come from coincidence, a third factor, or reverse causation, so experiments are the strongest way to show a cause.
Do I need Python to do statistics?
No. Excel and SQL cover descriptive statistics, correlation, and simple regression well. Python or R become useful for larger datasets, repeatable analysis, and tests that spreadsheets handle awkwardly.
How much data do I need?
It depends on the effect you want to detect and how variable the data is. Small effects and noisy data need larger samples. For important decisions, use a sample-size calculator before you collect data instead of guessing.
Conclusion
Good statistical analysis is mostly good habits: look at the data before the numbers, report the center and the spread, investigate outliers, be skeptical of correlations, quantify uncertainty with intervals, and test before you claim a difference is real. Start with describe() on every new column, and add one technique at a time as your questions get harder. If you need help turning your data into clear answers, you can book a free consultation.
The Python examples were run with pandas 3.1, NumPy 2.5, and SciPy 1.18, and the SQL functions were checked in a PostgreSQL-compatible engine. Results from random simulations vary with the seed and library version, and statistical functions can use slightly different defaults in other tools, so confirm the settings in the tool you use.
Related Reading
- What Is a Data Analyst? A Beginner’s Guide to Roles, Skills, and Tools
- Python for Data Analysis: Accessing Your Data
- Data Cleaning with Python Pandas: From Raw Data to Analysis
- Python Data Visualization: A Practical Guide to Charts & Graphs
- Data Analytics and Forecasting: From Insights to Predictions
- Machine Learning for Beginners: What It Is and How It Works
