IQR outlier calculator: quartiles, fences and a box plot
The interquartile range is IQR = Q3 − Q1, and a value is an outlier if it lies below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR. The catch: Q1 and Q3 depend on the quartile method. pandas, Excel, a TI-84 and R can give different quartiles for the same numbers, and so a different list of outliers.
Paste your numbers to get Q1, the median, Q3, the IQR, both fences and every outlier, under the method you choose and side by side under all 15. Drag a point on the box plot to see the fences move, compare removing, capping and replacing, and check the numbers in your report. Free, runs in your browser.
NumPy 2.5.5 and pandas 3.1.2 code and docs · matplotlib 3.11.2 boxplot · Hyndman and Fan 1996 · NIST e-Handbook · checked against an independent solution (77,498 checks at build, 26,857 NumPy, pandas, matplotlib and SciPy cross-checks) · Updated 1 Dec 2026
10 numbers read.
Ten exam marks. Q1 and Q3 change with the method, and so does whether 21 is an outlier.
Drag a dot sideways, or focus it and use the arrow keys (Shift for bigger steps), to change that value. Box: Q1 to Q3 with the median. Whiskers: to the furthest value inside the fences, as matplotlib draws them. Dashed: inner fences; dotted: outer fences (k = 3). Orange: outliers; red: beyond the outer fences.
The same data under every method (k as chosen). Click a row to use that method.
| Method | Q1 | Median | Q3 | Lower fence | Upper fence | Outliers | Used by |
|---|
import numpy as np import pandas as pd s = df["Annual Premium (in Rs)"] # one numeric column, not the whole DataFrame q1, q3 = s.quantile([0.25, 0.75]) # pandas default: linear (= NumPy method="linear") iqr = q3 - q1 lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr out = s[(s < lower) | (s > upper)] # NaN is never < or >, so blanks are not counted print(q1, q3, iqr, lower, upper, len(out))
Uses the data, method and k from tab 1. Each treatment uses the fences of the data as it is now; "found again" runs the same IQR rule on the treated data.
| Treatment | n | Mean | sd (n − 1) | Median | Values changed | Found again |
|---|
Remove the outliers, recompute the quartiles on what is left, repeat:
| Round | n | Q1 | Q3 | Lower fence | Upper fence | Removed |
|---|
Three rules on the same data
| Rule | Flags | Low | High | Centre and spread used |
|---|
z uses the mean and the standard deviation with n in the denominator (scipy.stats.zscore's default, ddof = 0); the modified z-score uses the median and the median absolute deviation, with Iglewicz and Hoaglin's 3.5 cut-off as NIST gives it.
Type what your report gives. The tool recomputes the IQR and fences, names the likely formula behind a wrong fence, tests the outlier count, and, if you paste the data, says which quartile method gives your Q1 and Q3.
- Type Q1 and Q3 at least, or fill an example.
Prints Q1, the median, Q3, the fences and the outlier count under every method, plus what pandas' quantile() and describe() return. Run: python iqr_script.py 3 7 8 9 10 11 12 13 14 21, or python iqr_script.py data.csv "annual premium (in Rs)"
"""Quartiles, IQR fences and outliers under every quartile method, with NumPy and pandas (the script on /tools/iqr-outlier-calculator).
Usage:
python iqr_script.py 3 7 8 9 10 11 12 13 14 21 # numbers on the command line
python iqr_script.py data.csv "annual premium (in Rs)" # one column of a CSV file
Prints Q1, median, Q3, the fences for k = 1.5 and how many values fall outside them for each NumPy method, Tukey's hinges and
the median-excluded halves rule, then what pandas' quantile() and describe() give. Needs numpy >= 1.22 (method= argument) and pandas.
"""
import sys
import numpy as np
import pandas as pd
K = 1.5
METHODS = ["linear", "weibull", "inverted_cdf", "averaged_inverted_cdf", "closest_observation", "interpolated_inverted_cdf",
"hazen", "median_unbiased", "normal_unbiased", "lower", "higher", "midpoint", "nearest"]
def hinges(v):
"""Tukey's hinges, as R's fivenum(): depth floor((n + 3) / 2) / 2 from each end."""
n = len(v)
d = np.floor((n + 3) / 2) / 2
h = lambda t: 0.5 * (v[int(np.floor(t)) - 1] + v[int(np.ceil(t)) - 1])
return h(d), np.median(v), h(n + 1 - d)
def halves(v):
"""Median of each half, the median itself left out when n is odd (the TI-84 rule)."""
h = len(v) // 2
return np.median(v[:h]), np.median(v), np.median(v[len(v) - h:])
def main():
if len(sys.argv) == 3 and sys.argv[1].endswith(".csv"):
s = pd.read_csv(sys.argv[1])[sys.argv[2]]
else:
s = pd.Series([float(a) for a in sys.argv[1:]])
s = pd.to_numeric(s, errors="coerce")
blanks = int(s.isna().sum())
v = np.sort(s.dropna().to_numpy(dtype=float))
print(f"n = {len(v)} values ({blanks} blank or non-numeric skipped) NumPy {np.__version__}, pandas {pd.__version__}")
print(f"{'method':<28}{'Q1':>14}{'median':>14}{'Q3':>14}{'lower fence':>14}{'upper fence':>14}{'outliers':>9}")
rows = [(m, *np.quantile(v, [0.25, 0.5, 0.75], method=m)) for m in METHODS]
if len(v) >= 1:
rows.append(("Tukey hinges (R fivenum)", *hinges(v)))
if len(v) >= 2:
rows.append(("halves, median excluded", *halves(v)))
for name, q1, med, q3 in rows:
iqr = q3 - q1
lo, hi = q1 - K * iqr, q3 + K * iqr
out = int(((v < lo) | (v > hi)).sum())
print(f"{name:<28}{q1:>14.6g}{med:>14.6g}{q3:>14.6g}{lo:>14.6g}{hi:>14.6g}{out:>9}")
q1, q3 = s.quantile([0.25, 0.75])
d = s.describe()
print(f"\npandas s.quantile([0.25, 0.75]) = {q1:.6g}, {q3:.6g}; s.describe(): 25% = {d['25%']:.6g}, 75% = {d['75%']:.6g}")
if __name__ == "__main__":
main()
Run with NumPy 2.5.5 and pandas 3.1.2 on the textbook set, it prints the same Q1, Q3, fences and outlier counts as the table in tab 1 (linear 8.25 and 12.75, weibull 7.75 and 13.25). The method= argument needs NumPy 1.22 or later; older versions called it interpolation= and had only linear, lower, higher, midpoint and nearest.
How do you find outliers using the IQR?
Sort the values, find the first and third quartiles, and build two fences from the distance between them. NIST's Engineering Statistics Handbook calls Q3 − Q1 the interquartile range and defines a lower inner fence Q1 − 1.5 × IQ and an upper inner fence Q3 + 1.5 × IQ, with outer fences at 3 × IQ: "A point beyond an inner fence on either side is considered a mild outlier. A point beyond an outer fence is considered an extreme outlier."
Worked example: ten exam marks, 3, 7, 8, 9, 10, 11, 12, 13, 14, 21. With pandas' default quartiles, Q1 = 8.25 and Q3 = 12.75, so IQR = 4.5, the lower fence is 1.5 and the upper fence 19.5. Nothing is below 1.5; 21 is above 19.5, so it is a (mild) outlier. The outer fences, -5.25 and 26.25, catch nothing, so there are no extreme outliers. A value exactly on a fence is not an outlier: matplotlib, R and the usual pandas line all use strict < and >.
Why do Excel, pandas and my textbook give different quartiles?
Because there is no single definition of a sample quartile. Hyndman and Fan (1996) listed nine, and software picked different ones. For the same ten marks, the 15 methods on this page give 10 different (Q1, Q3) pairs. Every one is a reasonable estimate; what matters is that you say which one you used, and that you do not mix them in one analysis.
Most methods find a position h in the sorted data and interpolate between the two values around it:
The two you meet most differ only in h. Type 7 is NumPy's and pandas' default ("linear"), R's default and Excel's QUARTILE.INC; type 6 is Excel's QUARTILE.EXC, and R's documentation says it "is used by Minitab and by SPSS". On the ten marks (x1 = 3 … x10 = 21):
That moves the upper fence across the value 21:
| Method (NumPy name) | H&F type | Q1 | Q3 | Upper fence | Is 21 an outlier? | Who uses it |
|---|---|---|---|---|---|---|
| linear | 7 | 8.25 | 12.75 | 19.5 | yes | pandas, NumPy, R and matplotlib default; Excel QUARTILE.INC / PERCENTILE.INC |
| weibull | 6 | 7.75 | 13.25 | 21.5 | no | Excel QUARTILE.EXC; Minitab and SPSS; Python statistics.quantiles default |
| Tukey hinges | – | 8 | 13 | 20.5 | yes | R fivenum() and boxplot(); median of halves with the median included |
| Median of halves, median excluded | – | 8 | 13 | 20.5 | yes | TI-83/84 calculators; Moore and McCabe's textbook rule |
| inverted_cdf | 1 | 8 | 13 | 20.5 | yes | inverse of the empirical CDF |
| averaged_inverted_cdf | 2 | 8 | 13 | 20.5 | yes | type 1 averaged at jumps (SAS default) |
| closest_observation | 3 | 7 | 13 | 22 | no | nearest even order statistic |
| interpolated_inverted_cdf | 4 | 7.5 | 12.5 | 20 | yes | linear interpolation of the empirical CDF |
| hazen | 5 | 8 | 13 | 20.5 | yes | popular with hydrologists |
| median_unbiased | 8 | 7.9167 | 13.0833 | 20.8333 | yes | recommended by Hyndman and Fan |
| normal_unbiased | 9 | 7.9375 | 13.0625 | 20.75 | yes | unbiased for normal order statistics |
| lower | – | 8 | 12 | 18 | yes | pandas interpolation='lower' |
| higher | – | 9 | 13 | 19 | yes | pandas interpolation='higher' |
| midpoint | – | 8.5 | 12.5 | 18.5 | yes | pandas interpolation='midpoint' |
| nearest | – | 8 | 13 | 20.5 | yes | pandas interpolation='nearest' |
Where the "who uses it" column comes from: NumPy's docstring numbers its nine recommended methods as they appear in Hyndman and Fan; R's quantile help page says type 6 "is used by Minitab and by SPSS" and type 7 is R's default; Microsoft's PERCENTILE.INC page says it interpolates when k "is not a multiple of 1/(n − 1)" and PERCENTILE.EXC when it is not a multiple of "1/(n + 1)", and both functions' own examples (QUARTILE.INC of 1, 2, 4, 7, 8, 9, 10, 12 is 3.5; QUARTILE.EXC of Microsoft's 11 values gives 15 and 43) come out of type 7 and type 6 exactly in our verifier. Tukey's hinges are what R's fivenum() and boxplot() use; Langford (2006) shows they equal the "median of each half, median included" rule. His tests of a TI-83 Plus, TI-84 Plus and TI-89 found the median-excluded rule instead, though the TI-83 Plus guidebook describes the other one. Python's statistics.quantiles() defaults to method "exclusive", which is type 6; "inclusive" is type 7.
Two details that trip people up. First, pandas' interpolation= offers only linear, lower, higher, midpoint and nearest; for Excel's QUARTILE.EXC numbers, call np.quantile(s.dropna(), [0.25, 0.75], method="weibull"). The argument was called interpolation= before NumPy 1.22. Second, NumPy's "nearest" rounds a position of exactly .5 to the even index (its code uses np.around), although its docstring describes g as "> 0.5"; our 17,667 NumPy cross-checks follow the code.
What each method does with tiny samples
Q1 / Q3 for the first n values of 10, 20, 40, 80:
| Method | n = 1 | n = 2 | n = 3 | n = 4 |
|---|---|---|---|---|
| linear | 10 / 10 | 12.5 / 17.5 | 15 / 30 | 17.5 / 50 |
| weibull | 10 / 10 | 10 / 20 | 10 / 40 | 12.5 / 70 |
| Tukey hinges | 10 / 10 | 10 / 20 | 15 / 30 | 15 / 60 |
| Median of halves, median excluded | refuses | 10 / 20 | 10 / 40 | 15 / 60 |
| inverted_cdf | 10 / 10 | 10 / 20 | 10 / 40 | 10 / 40 |
| averaged_inverted_cdf | 10 / 10 | 10 / 20 | 10 / 40 | 15 / 60 |
| closest_observation | 10 / 10 | 10 / 20 | 10 / 20 | 10 / 40 |
| interpolated_inverted_cdf | 10 / 10 | 10 / 15 | 10 / 25 | 10 / 40 |
| hazen | 10 / 10 | 10 / 20 | 12.5 / 35 | 15 / 60 |
| median_unbiased | 10 / 10 | 10 / 20 | 11.6667 / 36.6667 | 14.1667 / 63.3333 |
| normal_unbiased | 10 / 10 | 10 / 20 | 11.875 / 36.25 | 14.375 / 62.5 |
| lower | 10 / 10 | 10 / 10 | 10 / 20 | 10 / 40 |
| higher | 10 / 10 | 20 / 20 | 20 / 40 | 20 / 80 |
| midpoint | 10 / 10 | 15 / 15 | 15 / 30 | 15 / 60 |
| nearest | 10 / 10 | 10 / 20 | 10 / 40 | 20 / 40 |
The median-excluded halves rule has nothing left in each half at n = 1, so the page refuses. NumPy's methods never refuse: positions below the first value or above the last are clipped to the minimum or maximum, which is why "weibull" gives 10 / 20 at n = 2. Excel's QUARTILE.EXC returns #NUM! there instead ("If it cannot interpolate for the percentile ... Excel will return #NUM! error"), and Python 3.12.8's statistics.quantiles([10, 20]) extrapolates past the data to 7.5 and 22.5. With four values or fewer, a fence says very little whichever method you pick.
How does a box plot decide its whiskers?
The box spans Q1 to Q3 with a line at the median. matplotlib's documentation for whis (default 1.5): "the lower whisker is at the lowest datum above Q1 - whis*(Q3-Q1), and the upper whisker at the highest datum below Q3 + whis*(Q3-Q1) ... The default value of whis = 1.5 corresponds to Tukey's original definition of boxplots. ... Beyond the whiskers, data are considered outliers and are plotted as individual points." Its code (cbook.boxplot_stats) takes Q1 and Q3 from np.percentile, NumPy's linear method, and never lets a whisker end inside the box. seaborn's boxplot documentation says the same: "whiskers are drawn to the farthest datapoint within whis * IQR from the nearest hinge". R's boxplot.stats says "the whiskers extend to the most extreme data point which is no more than coef times the length of the box", with coef = 1.5, and uses Tukey's hinges, which "equal the quartiles for odd n ... and differ for even n".
So a whisker ends on a data value, not on the fence. On the ten marks, the upper whisker stops at 14 (the fence is 19.5) and 21 is drawn on its own. Our 144 comparisons with matplotlib 3.11.2's boxplot_stats agree on both whisker ends and the number of fliers. Drawn with weibull quartiles (Excel's QUARTILE.EXC numbers), the upper fence is 21.5 and 21 is inside the whisker:
Why 1.5 times the IQR, and when to use 3?
1.5 is Tukey's choice, and it is matplotlib's and R's default. What it means is easiest to see on a normal distribution. The quartiles sit 0.6745 standard deviations either side of the mean, so the IQR is 1.3490 σ and the inner fences are 2.6980 σ from the mean:
So even perfectly normal data puts about 0.70 % of its values beyond the inner fences: about 2,656 of 3,80,722 rows in a table the size of the insurance dataset. The outer fences (k = 3) are 4.721 σ out, where a normal distribution has 2.34 values per million (Python's statistics.NormalDist). Use 1.5 to find values worth a look and 3 for values that are almost certainly not from the same normal-looking process. For skewed data such as premiums, both flag mostly the long tail, not errors.
Should I remove outliers, cap them or replace them with the mean?
Decide why each one is there before you decide what to do. NIST's handbook: "Outliers should be investigated carefully. Often they contain valuable information about the process under investigation or the data gathering and recording process. Before considering the possible elimination of these points from the data, one should try to understand why they appeared and whether it is likely similar values will continue to appear. Of course, outliers are often bad data points." A premium of ₹5,40,165 can be a typing error, or a real customer with an expensive car; only the source data can tell you which. Our calculator cannot.
What each option does, on the 300 synthetic right-skewed premiums (linear quartiles, k = 1.5: 16 outliers, all on the high side):
| Treatment | n | Mean (₹) | sd (₹) | Median (₹) | Outliers found again | pandas |
|---|---|---|---|---|---|---|
| Keep them | 300 | 33,265 | 16,056 | 28,548 | 16 | s_keep = s |
| Remove the rows | 284 | 30,736 | 11,992 | 27,864 | 2 | s_removed = s[(s >= lower) & (s <= upper)] |
| Cap at the fences | 300 | 32,599 | 14,068 | 28,548 | 0 | s_capped = s.clip(lower=lower, upper=upper) |
| Replace with the median | 300 | 30,619 | 11,677 | 28,523 | 5 | s_med = s.mask((s < lower) | (s > upper), s.median()) |
| Replace with the mean (outliers still in it) | 300 | 30,871 | 11,680 | 28,548 | 5 | s_mean = s.mask((s < lower) | (s > upper), s.mean()) |
| Replace with the mean of the rest | 300 | 30,736 | 11,666 | 28,548 | 5 | s_mean2 = s.mask((s < lower) | (s > upper), s[(s >= lower) & (s <= upper)].mean()) |
Removing rows drops data you may need for other columns. Capping (s.clip at the fences) keeps every row and squeezes the tail onto the fence. Replacing with the median or the mean keeps every row but puts many identical values in the middle, which cuts the standard deviation and hides the spread. If you must replace with a mean, take it from the values that are not outliers: here that mean is ₹30,736 against ₹30,871 for a mean computed with the outliers still in the column.
Watch the last column. After any treatment, the quartiles of what is left are closer together, so new values fall outside the new fences. Removing and recomputing again and again on these premiums takes 4 rounds to settle and throws away 21 of 300 values (7.0 %). One pass is a choice; a loop until nothing is flagged eats into real data. The masking problem NIST describes for formal tests is related: "Masking can occur when we specify too few outliers in the test", because the other outliers inflate the test statistic.
IQR or z-score for outliers?
The IQR rule uses quartiles, which the outliers barely move. A z-score uses the mean and standard deviation, which the outliers themselves pull, and its usual cut-offs only make sense for roughly normal data. NIST restricts its outlier tests to "univariate data sets that are assumed to follow an approximately normal distribution", warns that using z-scores "can be misleading (particularly for small sample sizes) due to the fact that the maximum Z-score is at most (n − 1)/√n", and recommends the modified z-score of Iglewicz and Hoaglin, labelling |M| > 3.5 as potential outliers.
| Data | IQR rule (linear, 1.5) | |z| > 3 | Modified |M| > 3.5 |
|---|---|---|---|
| 300 synthetic premiums (right-skewed) | 16 (0 low, 16 high) | 4 (0 low, 4 high) | 10 (0 low, 10 high) |
| Ten exam marks | 1 | 0 (largest |z| possible: √9 = 3) | 0 |
| Ties preset (IQR = 0) | 3 | 1 | undefined: MAD = 0 |
On the skewed premiums the z-score flags fewer values than the IQR rule, because the long tail inflates the standard deviation to ₹16,030. With n = 10 and scipy's default standard deviation (n in the denominator), the largest |z| any value can reach is √(n − 1) = 3, so |z| > 3 can never fire. Ties break both robust rules: with more than half the values equal, the IQR or the MAD is 0, the IQR rule flags every value that differs from the box, and the modified z-score is undefined. None of these rules knows whether a value is wrong.
Worked example: annual premium in the vehicle insurance EDA
The "EDA on Vehicle Insurance Customer Data" project in Skill-Lync's PG Program in Data Analytics and Data Science gives two tables: customer details (8 columns: customer_id, gender, age, driving licence present, region code, previously insured, vehicle age, vehicle damage) and policy details (customer_id, annual premium (in Rs), sales channel code, vintage, response), joined on customer_id, with 3,81,109 rows and a few hundred nulls in every column (346 in annual premium). The brief asks for a column-wise count of outliers by the IQR method with 1.5 × IQR, Q1 and Q3 from pd.describe(), and replacing outliers "by mean". We did not have the course dataset, so the numbers below are the ones the public reports print, rechecked for consistency.
After dropping the rows with a null customer_id and filling premium nulls with the mean, describe() gives n = 3,80,722, mean ₹30,564, minimum ₹2,630 and maximum ₹5,40,165 (one report's output), and Q1 = 24,416, Q3 = 39,391.75, the quartiles printed most often (9 and 8 reports):
The minimum, ₹2,630, is above the lower fence, so there are no low outliers, as the reports print. Above ₹61,855.375 the most printed count is 10,332 (17 reports), and the smallest outlier they list is ₹61,858, just past the fence. That is 2.71 % of the rows, all on the high side, which is what a right-skewed premium column looks like, not 10,332 typing errors.
Order matters. A few reports compute the quartiles before filling the 344 premium nulls (3,80,378 values): Q1 = 24,407, Q3 = 39,401.75, fences 1,914.875 and 61,893.875, and 10,291 outliers. Filling adds 344 copies of the mean, ₹30,564, inside the box; they pull Q1 up by 9 and Q3 down by 10, the upper fence drops by 38.5, and the 41 premiums between ₹61,855.375 and ₹61,893.875 become outliers: 10,291 + 41 = 10,332.
Then the treatment. Replacing outliers with the mean is what the brief asks ("Replace all outlier values for numeric columns by mean"), so the question is which mean. The one most reports use, ₹30,564, is the column mean with the 10,332 outliers still in it (at least 56 of the 58 reports that replace with a mean), so it is higher than the mean of the other values. And after the replacement the quartiles move: one report prints Q1 = 24,416, Q3 = 38,335, minimum ₹2,630 and maximum ₹61,854 for the treated column (report). Its new fences are 3,537.5 and 59,213.5: the old minimum is now a low outlier and the old near-fence values are new high outliers. Reports that recheck with the old fences print 0 and miss this.
The whole-table slip. Run df.quantile() or describe() on the full table and customer_id gets quartiles too: Q1 = 95,276.25, Q3 = 2,85,818.75, upper fence 5,71,632.5, printed in 6 reports. An ID that runs from 1 to 3,81,109 can never have an outlier, and its "mean" means nothing. Binary columns are worse: driving licence present has Q1 = Q3 = 1, so IQR = 0 and every 0 is "an outlier" (811 rows printed in one report; 46,604 for response, whose quartiles are both 0). Codes such as region code and sales channel code are labels, not quantities. Test the measured columns only: annual premium, age and vintage.
What the 150 public vehicle insurance EDA reports do (as of 1 Dec 2026)
We read the 150 public Skill-Lync reports titled "Project 2 - EDA on Vehicle Insurance Customer Data" and close variants, as of 1 Dec 2026, n = 150. 4 are image-only (fewer than 15 lines and 100 words of their own text), which leaves 146 with text. Many show code or output only as screenshots, and our text copy loses some code symbols, so every count is a floor: read each as "at least". The links are examples.
- ≥ 132 / 146Mention outliers at all (heading, code or text). report 1report 2
- ≥ 75 / 146Compute Q1, Q3 and 1.5 x IQR fences in code. Every fence in the corpus uses k = 1.5; none uses k = 3, z-scores, percentile capping or a log transform. report 1report 2
- ≥ 47 / 146Take Q1/Q3 from describe() (the brief's Hint 2). describe() calls quantile() with the default linear method, so the numbers match .quantile(). report 1report 2
- ≥ 48 / 146Use .quantile(0.25) / .quantile(0.75). report 1report 2
- ≥ 5 / 146Use np.percentile. Two of these call np.percentile(1, [75, 25]) on the number 1, so their IQR is 0. report 1report 2
- ≥ 18 / 146Draw or mention a box plot. report 1report 2
- ≥ 18 / 146Run quantile() on the whole table, so Customer_Id and code columns get quartiles too. Printed evidence: customer_id Q1 95276.25, Q3 285818.75, upper fence 571632.5. report 1report 2
- ≥ 48 / 146Run the IQR outlier test on ID or code columns (customer_id, region code, sales channel code, driving licence, previously insured, response). Binary columns have IQR = 0 (e.g. driving licence present: Q1 = Q3 = 1), so every minority value is flagged; reports print 811 driving-licence and 46604 response "outliers". report 1report 2
- ≥ 19 / 146Overwrite "outliers" inside code columns with a mean, or drop rows on them. report 1report 2
- ≥ 58 / 146Replace outliers with a mean (what the brief asks). report 1report 2
- ≥ 56 / 58Replacement mean computed while the outliers are still in the column. Only 2 reports set the outliers to NaN first, so their mean excludes them. report 1report 2
- ≥ 15 / 75Count outliers with IQR but never treat them. report 1report 2
- ≥ 8 / 146Outlier "replace" helper that returns the column unchanged. def replace(df): computes q1, q3, upper, lower and then returns df untouched; the printed column is the original. report 1report 2
- ≥ 94 / 146Fill numeric nulls with the mean. report 1report 2
- ≥ 8 / 146Fill every null with the mean of all column means (Customer_Id included). customer_policy_details.fillna(customer_policy_details.mean().mean()): one number, averaged over customer_id, premium, channel, vintage and response, fills every column. report 1report 2
- ≥ 67 / 146Call drop_duplicates(). Every printed duplicated().sum() is 0. report 1report 2
What stands out for this calculator. At least 75 compute the fences in code, and none uses k = 3, a z-score or capping; at least 47 take Q1 and Q3 from describe(), as the brief hints, which is the same linear method as quantile(). Replacing outliers with the mean is the brief's instruction; of the 58 that do it, 56 take that mean with the outliers still in the column. At least 48 also run the test on ID or code columns, and 19 then overwrite those codes. At least 8 have a "replace" helper that returns the column unchanged. Since the method is fixed, almost all printed quartiles agree; the differences come from what was done to nulls first. These are first-party counts, a starting point rather than a measure of anyone's ability.
Common IQR slips and how to fix them
- Quartiles of the whole DataFrame. df.quantile(0.25) gives every column a Q1, including customer_id and codes (at least 18 reports). Fix:
s = df["annual premium (in Rs)"]; q1, q3 = s.quantile([0.25, 0.75]), or loop over a list of measured columns. - Outliers "found" and treated in ID, code or 0/1 columns. A 0/1 column has IQR = 0, so every minority value is flagged; at least 19 reports then overwrite those codes with a mean or drop the rows. Fix:
for c in ["annual premium (in Rs)", "age", "vintage"]:and leave codes alone. - A fence formula slip. q1 - 1.5*q3, (q1 - 1.5)*iqr, or the upper fence built from Q1. Tab 3 recognises each of these from your printed fences.
- fillna() or a helper whose result is thrown away. df["age"].fillna(df["age"].mean()) returns a new column and changes nothing unless you assign it; at least 8 reports have an outlier helper that returns its input untouched. Fix:
df["age"] = df["age"].fillna(df["age"].mean()), then print the count again. - Rechecking with the old fences. After a treatment, recompute Q1 and Q3 before you report "0 outliers left", and say whether you treat once or repeat.
- One fill value for every column. df.fillna(df.mean().mean()) fills premium, vintage and codes with one number averaged over columns, customer_id included (at least 8 reports). Fix: df.fillna(df.mean(numeric_only=True)) fills each column with its own mean.
How we checked the calculator
An independent Python script, scripts/verify/iqr.py, recomputes everything with its own code in plain Python: Hyndman and Fan's nine types from their 1-based definitions, the legacy NumPy methods, Tukey's hinges by splitting the data in halves, the fences, outliers, whisker ends, means and standard deviations, all six treatments, the removal rounds, z and modified z, parsing and the check tab. This page refuses to build if the browser code differs from it in any of 77,498 numbers, counts, indices or causes (683 cases, 440 of them random: n from 1 to 2,000, ties, negatives, values from 10−6 to 109 scales, skewed and spiked data, every method, k = 1.5 and 3; 7,900 more assertions run inside the script, among them R's claim that hinges equal type 7 quartiles for odd n, and Microsoft's own QUARTILE examples). Python 3.12.8's statistics.quantiles agreed in 2,595 comparisons ("inclusive" = type 7, "exclusive" = type 6). With NumPy 2.5.5, pandas 3.1.2, matplotlib 3.11.2 and SciPy 1.18.1, it also compared 26,857 values: np.quantile with all 13 method names, Series.quantile with its five interpolation options, describe(), matplotlib's boxplot_stats whiskers and fliers, scipy.stats.zscore and median_abs_deviation. 0 mismatches. Two deliberate bugs, type 7 computed at n·p instead of (n − 1)·p and an upper fence of Q3 + k·Q3, each make the build fail.
What this calculator does not cover
- Formal outlier tests such as Grubbs', the generalised ESD test or Dixon's Q test (NIST covers them), and multivariate outliers (Mahalanobis distance, isolation forests).
- Weighted quantiles (NumPy's weights= argument, inverted_cdf only) and grouped data.
- Skew-adjusted box plots (the medcouple) and log-transforming before the IQR rule, which often suits premiums and incomes better.
- Sample vs population variance. The standard deviations here divide by n − 1, as pandas .std() does; the sample variance calculator explains n vs n − 1.
Cleaning nulls, finding outliers and summarising a real customer table is the EDA project of Skill-Lync's PG program in data analytics and data science, after the pandas week of its Python course.
Frequently asked questions
How do you find outliers using IQR?
Sort the data and find Q1 and Q3, the 25th and 75th percentiles. The IQR is Q3 minus Q1. Any value below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR is an outlier. For our ten exam marks, pandas quartiles give fences of 1.5 and 19.5, so 21 is the only outlier.
Why 1.5 times the IQR?
It is Tukey's choice for box plots, and matplotlib's default whisker length. For normally distributed data the 1.5 × IQR fences sit 2.70 standard deviations from the mean and flag about 0.70 % of values. The 3 × IQR outer fences mark "extreme" outliers: about 2.3 per million normal values.
Why do Excel and pandas give different quartiles?
They use different rules for the position of a quartile in sorted data. pandas, NumPy and Excel's QUARTILE.INC interpolate at (n − 1)p + 1; QUARTILE.EXC, Minitab and SPSS use (n + 1)p. On ten exam marks this moves Q3 from 12.75 to 13.25 and decides whether 21 is an outlier. Neither is wrong; state which you used.
Should I remove outliers or cap them?
First find out why they are there. NIST's handbook says outliers should be investigated carefully and that they often contain valuable information. Remove a value only if it is an error. Capping at the fences keeps every row but changes the values. Replacing with the mean pulls the standard deviation down the most.
IQR or z-score for outliers?
Use the IQR for skewed data. A z-score uses the mean and standard deviation, which the outliers themselves inflate, and assumes a roughly normal shape. On our 300 right-skewed synthetic premiums the IQR rule flags 16 values and |z| > 3 flags 4. With ten values, no |z| can even pass 3.
How does a box plot decide its whiskers?
The box runs from Q1 to Q3 with a line at the median. In matplotlib and R, each whisker runs to the furthest data point that is still inside the 1.5 × IQR fence, so whiskers end on real values, not on the fence. Points beyond the whiskers are drawn one by one as outliers.
Does pandas describe() use the same quartiles as quantile()?
Yes. describe() gives the 25 %, 50 % and 75 % values that quantile() returns with its default linear interpolation, NumPy's method "linear". We checked this on 1,359 test values with pandas 3.1.2. To get Excel's QUARTILE.EXC numbers instead, use NumPy's method "weibull".
Related on Skill-Lync
- Sample vs population variance calculator (n vs n − 1, and why numpy and pandas give different standard deviations)
- Probability distribution calculator (mean, variance, skewness and kurtosis of a distribution, and normal probabilities)
- K-means clustering calculator (scaling and clustering in the same program)
- Confusion matrix calculator (precision, recall and F1 for the classification weeks)
- All free engineering tools
Sources
- NumPy 2.5.5: numpy.quantile docstring (method names, H&F numbering, the 1.22 rename of interpolation to method) and numpy/lib/_function_base_impl.py (_QuantileMethods, _lerp, index clipping).
- pandas 3.1.2: Series.quantile and DataFrame.quantile (interpolation options, numeric_only default False since 2.0), Series.describe.
- matplotlib 3.11.2: Axes.boxplot (whis) and cbook.boxplot_stats source; seaborn 0.13.2 boxplot (whis).
- R 4.6.0 documentation: stats::quantile (types 1 to 9), grDevices::boxplot.stats, stats::fivenum.
- Hyndman, R. J. and Fan, Y. (1996). Sample quantiles in statistical packages. The American Statistician 50(4), 361-365 (as cited and summarised by NumPy and R).
- Langford, E. (2006). Quartiles in elementary statistics. Journal of Statistics Education 14(3).
- Microsoft Support: QUARTILE.INC, QUARTILE.EXC, PERCENTILE.INC, PERCENTILE.EXC.
- NIST/SEMATECH e-Handbook of Statistical Methods: 7.1.6 What are outliers in the data?; 1.3.5.17 Detection of outliers (z-score bound, Iglewicz and Hoaglin's modified z-score, masking).
- Python 3.12.8 standard library: statistics.quantiles, statistics.NormalDist; SciPy 1.18.1: scipy.stats.zscore (ddof = 0 default).
- Skill-Lync, the 150 public vehicle insurance EDA reports, read 1 Dec 2026.