DS 227 · Week 7

Data Exploration I

Descriptive statistics and univariate EDA: describing the data, one variable at a time, before any model.

Knowledge Discovery in Data · University of the Philippines Cebu

Outline

Three questions about one variable

Key terms · 1 of 2

Nine terms for describing one column

EDA

Exploratory data analysis: looking at data with summaries and charts before testing any idea.

e.g. run describe() and draw a histogram before any model

variable (in statistics)

One measured characteristic that changes from row to row: in a table, one column. Not a Python variable, which is a name holding a value.

e.g. budget is a variable of each project; x = 5 is a Python variable

distribution

How a variable's values are spread out: which are common, which are rare, where they bunch up.

e.g. most budgets are ₱10–70M; a few reach ₱1.45B

mean

The ordinary average: add all the values, divide by how many there are.

e.g. [2, 3, 4, 11] → 20 ÷ 4 = 5

median

The middle value once sorted (the average of the middle two if the count is even). Half below, half above.

e.g. [2, 3, 4, 11] → (3 + 4) ÷ 2 = 3.5

mode

The value that appears most often. The only "typical" that works for words.

e.g. ["M", "L", "M", "S"] → "M"

range

Largest value minus smallest value: the full width the data covers.

e.g. [2, 3, 4, 11] → 11 − 2 = 9

variance

How spread out values are: the average squared distance from the mean (pandas divides by n − 1).

e.g. [2, 4, 6]: mean 4, squared distances 4, 0, 4 → 8 ÷ 2 = 4

standard deviation (SD)

The square root of the variance: how far a typical value sits from the mean, in the column's own units.

e.g. [2, 4, 6] → √4 = 2; in pandas .std()

Key terms · 2 of 2

Seven terms for shape and categories

percentile / quartile

The p-th percentile has p% of the values below it. Quartiles are the 25th, 50th and 75th percentiles: Q1, median, Q3.

e.g. if the 90th percentile of scores is 85, nine in ten scored below 85

IQR

Interquartile range: Q3 − Q1, the width of the middle half. Extreme values barely move it.

e.g. Q1 = 71, Q3 = 88.5 → IQR = 17.5

skew

Lopsidedness. Right-skewed: a long tail of large values (mean above median). Left-skewed: the mirror image. About 0: symmetric.

e.g. incomes are right-skewed: a few people earn far more

histogram

A bar chart of one numeric column: each bar counts how many values fall in one range.

e.g. ax.hist(income, bins=6)

bins

The equal-width ranges a histogram counts into. More bins give narrower bars, more detail and more noise.

e.g. scores 0–100 in 10 bins: 0–10, 10–20, …

box plot

A picture of the quartiles: a box from Q1 to Q3, a line at the median, whiskers, and dots for outliers.

e.g. df.boxplot(column="budget")

frequency table

Each category with how many times it appears (or its share). pandas builds it with value_counts().

e.g. Visayas 6, Mindanao 4, Luzon 2

Concept

Exploration comes before confirmation

"Exploratory data analysis, John Tukey's term, means examining the data with as few preconceptions as possible and letting it suggest the questions worth asking, before any hypothesis is tested."
Description precedes modelling
About the tool

Exploratory analysis is John Tukey’s idea

1952

Range bars

Mary Eleanor Spear draws an early form of the box plot.

1965

Princeton

Tukey founds Princeton’s statistics department; he also works at Bell Labs.

1970

Box plot

Tukey introduces the box-and-whisker plot.

1977

The book

Exploratory Data Analysis is published.

SourceWikipedia: John Tukey; Wikipedia: Box plot

About the tool

Where Tukey’s tools appear today

SourceWikipedia: John Tukey; pandas: DataFrame.boxplot

Runnable code

Code on these slides runs in the browser

As in week 6, a block with a ▶ Run / Edit button runs in the browser and can be changed and run again. The first run downloads Python and pandas, which takes 10 to 20 seconds; charts appear as pictures.

Two kinds of block

The small examples run here. Blocks that download the flood data have no button: the companion notebook runs them. The browser runs pandas 2.2, so text columns print as object instead of str.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Part A

Centre and spread

Two numbers that together summarize a variable.

Loading a table and selecting one column were covered in weeks 4–6. This part adds the numbers that describe that column: where its middle is (the centre) and how far its values lie from it (the spread).

Exercise · 3 min

describe(): a full summary in one call

Count, centre, spread and quartiles for a numeric column. It is run on every column before any conclusion is drawn.

scores is a pandas Series (one column of values) holding 12 exam scores. .describe() is a method: a function that belongs to the Series and is called with a dot.

Tasks

  1. Predict the median (50%) before running: the middle of the 12 sorted scores.
  2. Select ▶ Run / Edit and run the code.
  3. Change the last score, 95, to 195. Which lines of the summary change?

Result on the lecture laptop (select to reveal)

The median is 81.0, halfway between the 6th and 7th sorted scores (79 and 83). With 195: the mean rises to 86.75, the std to 36.0 and the max to 195.0; count, min, the quartiles and the median do not move.

scores = pd.Series([72, 85, 90, 60, 75, 88, 91, 55, 79, 83, 68, 95]) print(scores.describe().round(2))
  • count 1212 values that are not missing
  • mean 78.42the ordinary average: 941 ÷ 12
  • std 12.70standard deviation: a typical score sits about 12.7 points from the mean
  • 25% / 50% / 75%the quartiles: a quarter of scores are below 71, half below 81, three quarters below 88.5
  • min / maxlowest and highest score: a first check for unusual values
Review

Quartiles from week 5

The 25% / 50% / 75% rows are the Q1, median and Q3 from week 5's IQR fences, now used for description rather than outlier detection.

Reminder from week 5

quartile
sort the values and cut them into four equal-count groups; Q1 has 25% below it, Q3 has 75% below it
IQR
Q3 − Q1, the width of the middle half: 88.5 − 71 = 17.5 here

50% = the median

Half the values below, half above. A statement about order, so extremes barely move it.

Q1 to Q3 = the middle half

The box in a boxplot. It contains the usual values, regardless of the tails.

Same numbers, two uses

Week 5 used them to flag outliers; this week they describe the bulk of the data.

Conceptual model

Twelve scores, sorted and cut into quarters

12 scores sorted quartiles IQR fences 72 85 90 60 75 88 91 55 79 83 68 95 1 55 2 60 3 68 4 72 5 75 6 79 7 83 8 85 9 88 10 90 11 91 12 95 Q1 71 median 81 Q3 88.5 88.5 − 71 = 17.5 lower: 71 − 1.5 × 17.5 = 44.75 upper: 88.5 + 1.5 × 17.5 = 114.75 0 outside
Exercise · 3 min

Mean and median agree only for symmetric data

On tight, symmetric data they are nearly equal. One very large value moves the mean towards it, while the median is unchanged.

If a billionaire joins 49 teachers on a bus, the mean wealth becomes tens of millions while the median passenger is still a teacher.

Tasks

  1. Predict both pairs of numbers.
  2. Select ▶ Run / Edit and run the code.
  3. Change 120 to 1200. What happens to the mean, and to the median?

Result on the lecture laptop (select to reveal)

11.6 and 12.0, then 33.2 and 12.0. With 1200 the mean jumps to 249.2; the median stays 12.0, because it depends only on the middle value.

tight = pd.Series([10, 12, 11, 13, 12]) print(tight.mean(), tight.median()) skewed = pd.Series([10, 12, 11, 13, 120]) print(skewed.mean(), skewed.median())
  • pd.Series([10, 12, 11, 13, 12])one column of five values
  • print(a, b)print both numbers on one line: the mean first, then the median
  • 11.6 12.0mean (10 + 12 + 11 + 13 + 12) ÷ 5 = 58 ÷ 5; median: sorted 10, 11, 12, 12, 13, the middle one
  • 33.2 12.0166 ÷ 5; the 120 alone lifts the mean. Sorted, the middle value is still 12

Which to report

For skewed data (incomes, house prices, wait times) the median is the appropriate "typical" value. Reporting both is better, since their gap is itself informative.

Output

One large value moves the mean but not the median

import matplotlib.pyplot as plt # tight, skewed: from the previous slide fig, ax = plt.subplots(figsize=(7, 2.6)) for y, s in [(1, tight), (0, skewed)]: ax.scatter(s, [y] * len(s), c="grey") ax.scatter(s.mean(), y, marker="^", s=150, c="red") ax.scatter(s.median(), y, marker="|", s=600, c="blue") ax.set_yticks([0, 1], ["skewed", "tight"]) ax.set_ylim(-0.6, 1.6) ax.legend(["value", "mean", "median"]) plt.show()
Two rows of dots on a number line from 10 to 120. Top row, tight: five grey dots between 10 and 13, with the red mean triangle and the blue median tick on top of each other near 12. Bottom row, skewed: four dots between 10 and 13 and one dot alone at 120; the median tick stays at 12 while the mean triangle sits at about 33.

in the tight row the mean (▲) and median (|) coincide. In the skewed row the single 120 drags the mean to 33.2, far from every actual value, while the median stays at 12 with the other four.

Exercise · 3 min

Same mean, very different spreads

Standard deviation (SD, std) measures how far values typically sit from the mean. The range is the largest minus the smallest value. Two series can have the same centre and differ in every other respect.

Tasks

  1. Predict which series has the larger standard deviation.
  2. Select ▶ Run / Edit and run the code.
  3. Change wild to [30, 70, 50, 50, 50]. What happens to the SD and the range?

Result on the lecture laptop (select to reveal)

wild: SD 31.6 against calm’s 0.7, with the same mean of 50. With [30, 70, 50, 50, 50] the SD falls to 14.1 and the range to 40; the mean is still 50.

calm = pd.Series([50, 51, 49, 50, 50]) print(calm.mean(), round(calm.std(), 1), calm.max() - calm.min()) wild = pd.Series([10, 90, 30, 70, 50]) print(wild.mean(), round(wild.std(), 1), wild.max() - wild.min())
  • round(calm.std(), 1)the standard deviation, rounded to one decimal
  • calm.max() - calm.min()the range: largest minus smallest
  • 50.0 31.6 80mean, SD, range: the same centre as calm, forty-five times the spread

Limitation of the mean alone

A river with an average depth of 1 meter can still have dangerously deep parts. The mean does not describe them; the spread does. The next slide computes the SD of wild by hand.

Worked example

A standard deviation, by hand

Take wild = [10, 90, 30, 70, 50], whose mean is 50. Four steps turn the distance from the mean into one number.

ValueDistance from 50Squared
10−401,600
90+401,600
30−20400
70+20400
5000

Squaring prevents the negative and positive distances from cancelling out; the square root at the end turns the answer back into the original units.

wild = pd.Series([10, 90, 30, 70, 50]) print(((wild - wild.mean())**2).sum()) print(wild.var()) # 4000 / (5 - 1) print(wild.std()) # square root of 1000 4000.0 1000.0 31.622776601683793
  • wild - wild.mean()subtracts 50 from every value at once: the distances
  • (…)**2 … .sum()square each distance and add them up: 1,600 + 1,600 + 400 + 400 + 0
  • wild.var()the variance: that total divided by n − 1 = 4 (pandas' choice for a sample)
  • wild.std()√1000 ≈ 31.6: a typical value is about 32 away from 50
Output

Equal means, standard deviations of 0.7 and 31.6

import matplotlib.pyplot as plt # calm, wild: from the spread exercise fig, ax = plt.subplots(figsize=(7, 2.6)) for y, s in [(1, calm), (0, wild)]: ax.scatter(s, [y] * len(s)) # a bar from mean - SD to mean + SD ax.errorbar(s.mean(), y + 0.3, xerr=s.std(), capsize=6, c="black") # both means are 50 ax.axvline(50, c="grey", ls="--") ax.set_yticks([0, 1], ["wild", "calm"]) ax.set_ylim(-0.5, 1.7) plt.show()
Two rows of dots around a dashed line at 50. Top row, calm: five dots between 49 and 51, with a very short black bar above them. Bottom row, wild: five dots at 10, 30, 50, 70 and 90, with a long black bar from about 18 to 82.

both rows balance on the dashed line at 50. Each black bar spans the mean ± one standard deviation: 0.7 for calm, barely visible, and 31.6 for wild. The mean alone does not distinguish them.

Case study

The flood data, loaded from the course API

The same summaries, now on the 34,079 flood control projects. The download is week 6’s, and so is the derived duration column that a later slide uses.

Why not pd.read_csv(url)?

pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.

The browser cannot download the data, so the flood blocks have no Run button; the companion notebook runs them.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" resp = requests.get(url, timeout=60) df = pd.read_csv(io.StringIO(resp.text)) # week 6's derived column, needed later today for col in ["start_date", "completion_date"]: df[col] = pd.to_datetime(df[col], errors="coerce") df["duration"] = (df.completion_date - df.start_date).dt.days print(df.shape) (34079, 16)
  • requests.get(url)download the whole table in one request
  • df["duration"] = …days from start to completion (week 6); NaN where a date is missing
  • (34079, 16)34,079 projects; 15 columns from the file plus duration
Case study

describe() on 34,079 budgets

One call gives every summary from Part A. It is read top to bottom before anything is plotted. df is the flood-control table (34,079 projects); df.budget is a shortcut for df["budget"], its budget column in pesos.

Indicator: mean vs 50%

They differ by ₱9.3 million here. On a symmetric distribution (the left half a mirror image of the right) they would be nearly equal. This one is skewed.

pd.set_option("display.float_format", "{:,.0f}".format) print(df.budget.describe()) count 34,079 mean 46,952,340 std 48,594,319 min 0 25% 14,649,406 50% 37,676,233 75% 67,549,270 max 1,447,499,996 Name: budget, dtype: float64
  • pd.set_option(…)a display setting, as in week 5: show numbers with commas and no decimals
  • mean 46,952,340the average project budget: about ₱47 million
  • 50% 37,676,233the median: half the projects cost less than ₱37.7 million
  • min 0 / max 1,447,499,996some rows record a zero budget; the biggest is ₱1.45 billion
Note

describe() excluded 6,415 rows without warning

Every statistic it printed describes only the remaining rows.

The count line

The count line is the only sign of the omission

duration is the column built in week 6: days from start date to completion date. Summarized on a 34,079-row frame, it gives count 27,664. pandas raised no error and no warning; it excluded the missing values and continued.

The 6,415 excluded rows are the unfinished projects

Exactly the On-Going, For Procurement and Not Yet Started projects from week 5. Therefore "median duration 202 days" means "median duration of projects that finished".

print(len(df)) print(df.duration.describe()["count"]) # always compare the two print(round(df.duration.isna().sum() / len(df), 3)) 34079 27664.0 0.188
  • len(df)counts the rows of the table
  • describe()["count"]selects one line of the summary by its label: how many values were actually used (27664.0 has a decimal because describe() stores every line as a decimal number)
  • isna().sum()isna() marks each missing cell (NaN) True; .sum() counts the Trues, because True counts as 1
  • 0.1886,415 ÷ 34,079: almost one row in five has no duration
Stating the population

The same statistic with two captions

✗ "Flood control projects take a median of 202 days"

Implies all 34,079. It describes a population that was never measured, since unfinished projects have no duration by definition.

Why this error is common

It is what .describe() appears to say, and only the count line in the output contradicts it.

✓ "Of the 27,664 completed projects, the median took 202 days"

States the population, the count and the statistic. A reader can check it and knows what it excludes.

Guideline

State the denominator in the sentence. If it cannot be stated, the measured quantity is not yet understood.

Two typical values, one column

A 25% gap: choosing which value to quote

Spread

A standard deviation larger than the median

₱48.6M of standard deviation (SD) against a ₱37.7M median is a warning in itself. For bell-shaped data, about 95% of values sit within 2 SDs of the mean (the "mean ± 2 SD" rule). Here that range would reach below zero.

Limitation of the SD

It assumes a roughly symmetric distribution. For skewed amounts, percentiles are preferable because they are always interpretable.

print(round(df.budget.std())) # mean - 2*SD is NEGATIVE print(46_952_340 - 2*48_594_319) 48594319 -50236298
  • round(df.budget.std())the standard deviation of every budget, rounded to whole pesos
  • 46_952_340the underscores are digit separators, like commas; Python ignores them
  • -50236298about −₱50.2M: mean minus two SDs is a negative budget: impossible, so the bell-shape rule does not apply
Skewness

A skew of 5.13 indicates strong right skew

Skewness (skew) puts a number on lopsidedness. Positive means a long tail of large values; negative, a long tail of small ones. Roughly: |skew| (the size, ignoring the sign) under 0.5 is symmetric, over 1 is strong.

Kurtosis 76 indicates a heavy tail

Kurtosis measures how often extreme values turn up. A normal distribution (the symmetric bell curve) scores 0 in pandas. 76 means extreme values are far more common than a bell curve would predict.

print(round(df.budget.skew(), 2)) print(round(df.budget.kurtosis(), 2)) # for comparison, a normal sample: bell = np.random.default_rng(0).normal(size=34079) print(round(pd.Series(bell).skew(), 4)) 5.13 76.01 -0.0072
  • np.random.default_rng(0).normal(size=34079)NumPy draws 34,079 random numbers from a bell curve (the 0 is a seed, so the draw repeats exactly)
  • round(pd.Series(bell).skew(), 4)wrap them in a Series so pandas can measure the skew, rounded to 4 decimals: about 0, as a symmetric shape should be
Percentiles and mean±SD

Each percentile translates into a plain statement

For skewed data, a set of percentiles is the preferred summary. The p-th percentile is the value with p% of the data below it. Each one is directly interpretable without assuming any shape.

p99 as a threshold for large projects

₱212M. Projects above it are the top 1% of 34,079 contracts, a much clearer threshold than "two standard deviations".

pd.reset_option("display.float_format") # undo the comma setting p = df.budget.quantile([.05, .25, .5, .75, .9, .99]) print((p / 1e6).round(1)) # in millions of pesos 0.05 1.9 0.25 14.6 0.50 37.7 0.75 67.5 0.90 96.5 0.99 212.1 Name: budget, dtype: float64
  • quantile([.05, .25, …])a list of fractions: .05 asks for the 5th percentile, .5 for the median
  • (p / 1e6).round(1)divide by one million (1e6) and keep one decimal, so ₱96,499,614 reads 96.5
  • 0.90 96.590% of projects cost less than ₱96.5 million
Concentration

Distribution of the ₱1.6 trillion across projects

Slice of projectsCountShare of total spend
Top 1% by budget3406.5%
Bottom 50% by budget17,03916.5%
The middle16,70077%
Concentration, drawn

Share of the money against share of projects

# budgets, smallest first b = df.budget.sort_values().to_numpy() # running share of the money share = b.cumsum() / b.sum() # share of the projects counted so far frac = np.arange(1, len(b) + 1) / len(b) fig, ax = plt.subplots() ax.plot(frac, share) # the line if every budget were equal ax.plot([0, 1], [0, 1], ls="--", c="grey") ax.set_xlabel("Share of projects (smallest first)") ax.set_ylabel("Share of the money") plt.show() # the bottom 50% of projects print(round(share[len(b) // 2 - 1], 3)) 0.165
A curve from the bottom left to the top right of a square, below a dashed diagonal. The x axis is the share of projects, smallest budget first; the y axis is the share of all the money. The curve stays low at first, passes about 0.17 at the halfway point, and rises steeply near the right edge.

the dashed diagonal is what equal budgets would give. The curve runs below it: the smaller half of projects holds 16.5% of the money, the “Bottom 50%” row of the previous slide. A few dominant projects would push the curve much closer to the bottom edge.

Review question

Question (select to reveal the answer)

Two sections took the same exam. Both average 75. Section A's std is 3; Section B's is 18. Which section is of greater concern?

A · Neither — the averages match
B · Section A — low variety means cheating
C · Section B — same centre, but many students far above and far below 75
D · Both equally, always

C: the spread reveals students who are struggling.

With std 18, Section B plausibly has students in the 40s, which Section A does not. The means are identical but the classes differ, which is why a mean is reported with its spread.

Break

  Five minutes

Next: shape, which the summary numbers do not show.

Part B

Shape

The shape of a distribution is shown by plotting it.

A column can now be summarized in a few numbers. Numbers hide the shape; this part plots it, with histograms, box plots and a log scale.

Exercise · 3 min

A histogram shows where values occur

The range is divided into bins (equal-width ranges, like 15–20k, 20–25k), the values in each are counted, and each count is drawn as a bar. Clusters, gaps and tails become visible, which no single number can show.

People grouped by height band (150–155 cm, 155–160 cm…), where the length of each queue is a bar.

Tasks

  1. Predict how many of the 12 incomes fall in the tallest bar.
  2. Select ▶ Run / Edit and run the code.
  3. Change bins=6 to bins=3. What happens to the 60k income, and to the rest?

Result on the lecture laptop (select to reveal)

10 of the 12 incomes are in the tallest bar (15k to 22.5k); one more sits in the next bar, and the 60k income stands alone at the right. With bins=3 the other eleven merge into one bar of 11, and 60k is still alone. The next two slides show both charts.

import matplotlib.pyplot as plt income = pd.Series([15, 18, 20, 22, 19, 21, 17, 60, 16, 23, 18, 20]) fig, ax = plt.subplots() ax.hist(income, bins=6) ax.set_xlabel("Income (k)") ax.set_ylabel("Count") plt.show()
  • fig, ax = plt.subplots()start a blank chart: fig is the whole picture, ax the plotting area (matplotlib, imported as plt)
  • ax.hist(income, bins=6)income is a Series of 12 incomes (in thousands); count them into 6 equal-width bins, one bar per bin
  • set_xlabel / set_ylabellabel the axes: what is across, what is up
  • plt.show()display the finished chart

Reading order

First the tallest bar (where most values are), then the number of peaks, then the direction of the tail.

Output

One tall bar and one isolated income far to the right

Histogram of the 12 incomes in thousands with 6 bars: a tall bar of 10 incomes from 15 to 22.5k, a short bar of 1 income from 22.5 to 30k, an empty stretch from 30 to 52.5k, and a short bar of 1 income from 52.5 to 60k.
Note

The number of bins changes the picture

The same twelve incomes with bins=6 and bins=3: the outlier (60k) stands alone in both, but with bins=3 all eleven other incomes merge into one bar and the 23k income is no longer distinguishable. Neither is the correct picture; both are choices.

Bins resemble the mesh of a fishing net, where large holes put everything into one catch and small holes give every fish its own pocket.

Too few bins

Everything merges into one block; structure and outliers disappear.

Too many bins

Every value gets its own bar, and noise appears as pattern.

Guideline

Try several bin counts before drawing conclusions. A "finding" that appears at only one bin setting is probably an effect of the bins.

Output

bins=6 and bins=3 for the same twelve incomes

Histogram with 6 bins: bars of 10, 1, 0, 0, 0 and 1 incomes, with bin edges every 7.5k from 15 to 60.Histogram with 3 bins: a bar of 11 incomes from 15 to 30k, an empty bin from 30 to 45k, and a bar of 1 income from 45 to 60k.
Plot

Histogram of the budget column

Everything above (the skew, the heavy tail, the gap between mean and median) appears in one picture, which should be plotted before the numbers are trusted.

Clipping the axis to show the bulk

With a ₱1.45B maximum, 95% of the data falls into the first four of 50 bars. The range is limited, and the limit is stated.

df.budget.hist(bins=50) plt.show() # 43% of projects in the first bar (under PHP 29M) # readable version: clip, and say so in the caption df.budget[df.budget < 2e8].hist(bins=50) plt.show()
  • df.budget.hist(bins=50)pandas' shortcut: draw a histogram of the column with 50 bins (it draws a picture and prints nothing; the # → comments describe the result)
  • 2e8e-notation: 2 followed by 8 zeros, i.e. 200,000,000 (₱200 million)
  • df.budget[df.budget < 2e8]keep only budgets under ₱200M (a boolean filter: keep the rows where the test is True), then draw those
Output

All 50 bars, then the clipped version

Histogram of all 34,079 budgets with 50 bars, x axis from 0 to 1.45 billion pesos (marked 1e9): one bar near zero reaches about 14,500 projects, a few bars follow, and the rest of the axis is almost empty.Histogram of the 33,720 budgets under 200 million pesos with 50 bars, x axis marked 1e8: many bars below 50 million, the tallest spike just under 50 million (about 3,300 projects), a second spike just under 100 million (about 2,400), then a long thin tail to 200 million.
Effect of bins

Three bin settings for the same 33,000 projects

BinsBin widthTallest bar holdsAppearance
10₱20.0M11,817 projectsOne dominant block; detail lost
30₱6.7M4,891 projectsA clear peak and tail; usable
100₱2.0M3,192 projectsSpiky; noise becomes visible
Types of skew

Symmetric, right-skewed, left-skewed

Output

Three shapes and their skew values

import numpy as np import matplotlib.pyplot as plt rng = np.random.default_rng(0) shapes = { "symmetric": rng.normal(50, 10, 1000), "right-skewed": rng.exponential(10, 1000), "left-skewed": 100 - rng.exponential(10, 1000), } fig, axes = plt.subplots(1, 3, figsize=(10, 3)) for ax, (name, x) in zip(axes, shapes.items()): ax.hist(x, bins=30) skew = pd.Series(x).skew() ax.set_title(f"{name}: skew {skew:.1f}") plt.show()
Three histograms of 1,000 random values each. Left, symmetric: a bell shape centred near 50, skew −0.1. Middle, right-skewed: tallest bars near 0 and a long tail to the right, skew 2.1. Right, left-skewed: tallest bars near 100 and a long tail to the left, skew −1.8.

the sign of the skew points along the tail: positive for a tail to the right, negative for a tail to the left, about 0 for a mirror image. The flood budgets (skew 5.13) lean the same way as the middle panel, more strongly.

Skewed shapes

Changing the scale, not the data

A log transform does not delete the outliers; it re-spaces the axis.

log₁₀(x) is the power of 10 that gives x: log₁₀(1,000) = 3, log₁₀(1,000,000) = 6. Each step of 1 means "ten times bigger".

Log transform

Skew 5.13 becomes −0.82

Money is often roughly log-normal: its logs look like a bell curve, because differences that matter are multiplicative (×2, ×10) rather than additive (+₱1M). Plotting log₁₀(budget) turns that shape into a near-symmetric one.

Plotting in logs, reporting in pesos

The transform is for visualization. Values are converted back before being quoted, so that readers need not exponentiate.

lb = np.log10(df.budget[df.budget > 0]) print(round(lb.skew(), 2)) # the log-mean, back in pesos print(round(lb.mean(), 2)) print(round(10**lb.mean())) -0.82 7.47 29733984
  • df.budget[df.budget > 0]keep the positive budgets: the log of 0 does not exist
  • np.log10(…)NumPy takes log₁₀ of every value: ₱10M becomes 7, ₱100M becomes 8
  • round(10**lb.mean())** is "to the power of": undo the log. The result is the geometric mean, a typical value on the multiplying scale
Output

The budget histogram before and after the log transform

lb = np.log10(df.budget[df.budget > 0]) millions = df.budget / 1e6 fig, (a1, a2) = plt.subplots(1, 2, figsize=(10, 3.5)) a1.hist(millions, bins=50) a1.set_title(f"budget: skew {millions.skew():.2f}") a1.set_xlabel("PHP millions") a2.hist(lb, bins=50) a2.set_title(f"log10(budget): skew {lb.skew():.2f}") plt.show()
Two histograms side by side. Left: budget in PHP millions, skew 5.13; almost all bars are crowded below 200 and the axis runs empty to 1,400. Right: log10 of budget, skew −0.82; the bars spread from about 5.5 to 9, with the tallest spikes near 7.7 and 8.0.

the same projects on two scales. On the right, 7 means ₱10 million and 8 means ₱100 million, so the crowded corner on the left is spread across the full width. The spikes near 7.7 and 8.0 are the clusters just under ₱50M and ₱100M seen in the clipped histogram.

Week 5's rule as a chart

The boxplot is the IQR rule as a picture

lower fence Q1 median Q3 upper fence outlier whiskers reach the last point inside 1.5 × IQR
Boxplot of real budgets

Week 5’s IQR rule as a boxplot

The box is p25 to p75 (Q1 to Q3). The whiskers reach 1.5×IQR beyond the box: the top fence is 67.5M + 1.5 × 52.9M = 146.9M. Everything beyond is drawn as a point — the same 798 projects week 5 flagged.

Best for comparing groups

One box per region puts 18 distributions side by side, which a histogram cannot do legibly.

q1, q3 = df.budget.quantile([.25, .75]) fence = q3 + 1.5 * (q3 - q1) # week 5: the upper fence print(round(fence / 1e6, 1), (df.budget > fence).sum()) df.boxplot(column="budget", by="region") plt.show() 146.9 798
  • q3 + 1.5 * (q3 - q1)week 5’s upper fence: 67.5M + 1.5 × 52.9M = ₱146.9 million
  • (df.budget > fence).sum()798 projects lie above it: the dots on a single national box
  • df.boxplot(column="budget", by="region")one box per region, side by side; on skewed data, expect dots: they are the tail, not errors
Output

Eighteen boxes with overlapping labels

pandas boxplot of budget by region with the title Boxplot grouped by region, budget; 18 boxes in alphabetical order along the x axis, whose region names overlap into an unreadable strip; the first box, Central Office, is much taller and higher than the rest, and most other boxes are squashed near zero with columns of outlier circles above them; y axis in billions of pesos (1e9).
Choice of chart

Histogram for detail, boxplot for comparison

They summarize the same distribution at different levels of detail, so they answer different questions.

Histogram

For a first look at a variable, showing its full shape: peaks, gaps and tails.

Boxplot

For a compact summary, especially several side by side: income by region, scores by section.

Link to next week

"Boxplots side by side" is already a two-variable question, which is where Data Exploration II begins.

Review question

Question (select to reveal the answer)

Household income in a city is strongly right-skewed. Without computing anything: how do its mean and median compare?

A · Mean > median — the long right tail pulls the mean up
B · Mean < median
C · Exactly equal, by definition
D · Impossible to say anything

A: the tail pulls the mean upward.

A few very high incomes lift the mean well above what a typical household earns; the median stays with the bulk of households. For this reason "median income" is more informative than "average income".

Part C

Categories and the EDA routine

Variables with no mean, and a checklist that covers every column.

Numeric columns can now be described. Text columns such as region or contractor have no mean; this part counts them, then gathers every check into one routine.

Exercise · 3 min

Categories are counted, not averaged

A categorical column holds labels, not amounts (region, status). Its summary is a frequency table: each value and how often it appears. value_counts() builds it, and with normalize=True gives each value's share.

Tasks

  1. Predict the share of Visayas.
  2. Select ▶ Run / Edit and run the code.
  3. Replace the last line with print(r.describe()). What does describe() report for text?

Result on the lecture laptop (select to reveal)

Visayas holds 0.50 (6 of 12). For text, describe() reports count 12, unique 3, top Visayas and freq 6: counts and the mode, because text cannot be averaged.

r = pd.Series(["Visayas"] * 6 + ["Mindanao"] * 4 + ["Luzon"] * 2, name="region") print(r.value_counts()) print(r.value_counts(normalize=True).round(2))
  • r = pd.Series([…] * 6 + …)an example column of 12 region labels: * 6 repeats a label six times, + joins the lists
  • r.value_counts()count the rows for each region, biggest first: 12 rows in total
  • normalize=Truedivide each count by the total: 6 ÷ 12 = 0.50. The shares add up to 1 (proportion = share)

Counts vs shares

Counts give "how many"; shares give "how dominant", and shares remain comparable across datasets of different sizes.

Categories

On real data: 18 regions, 4,841 contractors

The whole Part A toolkit is for numbers. For text columns, the summary is a frequency table, and the "typical" value is the mode: the value that appears most often.

Checking the number of unique values first

18 regions is groupable. 4,841 contractors is a long tail. 33,325 different descriptions is free text, which requires a different tool.

print(df.region.value_counts(normalize=True).round(3).head(4)) print(df.region.nunique(), df.contractor.nunique()) # mode = the most common value print(df.region.mode()[0]) region Region III 0.159 National Capital Region 0.115 Region I 0.103 Region IV-A 0.101 Name: proportion, dtype: float64 18 4841 Region III
  • .head(4)show only the first four lines: Region III holds 15.9% of projects
  • nunique()how many different values the column has
  • mode()[0]mode() returns a list-like Series, since two values can tie; [0] takes the first
Output

Projects per region, largest first

counts = df.region.value_counts() fig, ax = plt.subplots(figsize=(7, 5)) counts.sort_values().plot.barh(ax=ax) ax.set_xlabel("Projects") ax.set_ylabel("") plt.show()
Horizontal bar chart of project counts for 18 regions, sorted from most to fewest. Region III is longest at about 5,400, followed by the National Capital Region at about 3,900 and Regions I and IV-A near 3,500. Central Office is shortest, at under 200.

sorted bars make the frequency table readable at a glance: Region III, the mode, holds 15.9% of projects, and Central Office has only 180. A pie chart of 18 slices would not show this ranking.

Exercise · 8 min

Describing one column

1 · Pick a number column

Use duration (built in week 6) or progress (percent complete, 0–100). Run .describe().

2 · Measure the lean

Compute .skew(). Predict the histogram shape from that number alone, then plot it and check.

3 · Try three bin counts

10, 30, 100. Choose one for a report and state the reason.

4 · Write three sentences

One about the centre, one about the spread, one about the shape — each with a number in it.

Review question

Question (select to reveal the answer)

Flood budgets have mean ₱46.95M, median ₱37.68M and skew 5.13. Which sentence is the most accurate summary?

A · "The average flood control project costs ₱47 million"
B · "Half of projects cost under ₱38 million; the distribution is strongly right-skewed"
C · "Projects cost ₱47M ± ₱49M"
D · "Most projects cost close to ₱47 million"
B. A is arithmetically true but suggests a typical project that does not exist. C implies symmetry, but mean minus 2 SD is negative here, which is impossible for a budget. D is false: the mode is well below the mean. With skew 5.13, the median should be quoted and the skew stated.
Review question

Question (select to reveal the answer)

Taking log₁₀ of the budget column changes the skew from 5.13 to −0.82. What has this achieved?

A · Removed the outliers from the dataset
B · Re-spaced the axis so the shape is visible — every row is still there
C · Corrected an error in the data
D · Made the mean equal the median
B. A log transform changes the scale, not the data. All 34,079 projects remain, in the same order. It works here because money tends to be log-normal: the differences that matter are multiplicative. Plots use logs, but figures are converted back to pesos before being quoted.
Routine

The univariate EDA checklist

ECDF

The fraction below a threshold, without binning

A histogram requires a choice of bins. The ECDF (empirical cumulative distribution function) does not: for any chosen threshold, it gives the share of the data below it.

Interpretation

Each output is a claim suitable for a report, with no modelling assumption behind it.

print(round((df.budget < 1e7).mean(), 3)) print(round((df.budget < 5e7).mean(), 3)) print(round((df.budget < 1e8).mean(), 3)) # the projects of PHP 100M or more, and their share of the money big = df.budget >= 1e8 print(round(big.mean(), 3), round(df.budget[big].sum() / df.budget.sum(), 3)) 0.214 0.709 0.936 0.064 0.227
  • df.budget < 1e7compare every budget with 1e7 = 10,000,000: one True or False per project
  • ( … ).mean()True counts as 1 and False as 0, so the mean is the share that is True
  • 0.064 0.2276.4% of projects cost ₱100M or more, and they hold 22.7% of all the money
Output

The ECDF of the budget column

# budgets in PHP millions, smallest first x = np.sort(df.budget.to_numpy()) / 1e6 # share of projects at or below each budget y = np.arange(1, len(x) + 1) / len(x) fig, ax = plt.subplots() ax.plot(x, y) for t in [10, 50, 100]: # the three thresholds ax.axvline(t, c="grey", ls=":") ax.set_xlim(0, 200) ax.set_xlabel("Budget, PHP millions") ax.set_ylabel("Share of projects below") plt.show()
A rising step curve. The x axis is budget in PHP millions from 0 to 200; the y axis is the share of projects below, from 0 to 1. Dotted vertical lines mark 10, 50 and 100. The curve crosses about 0.21 at 10, jumps to about 0.71 at 50, and reaches about 0.94 just after 100, then flattens near 1.

the three dotted lines are the thresholds printed on the previous slide: 21.4% of projects lie below ₱10M, 70.9% below ₱50M and 93.6% below ₱100M. The vertical jumps just below ₱50M and ₱100M are budgets clustered under those round figures.

Spread across units

CV makes spread in pesos and days comparable

A standard deviation of 48 million pesos and one of 159 days cannot be compared. The coefficient of variation (CV) divides each SD by its own mean, so the units cancel and both become plain numbers.

Guideline

CV above 1 means the spread exceeds the average, which indicates skew or heavy tails. Budget sits at 1.03.

def cv(x): return x.std() / x.mean() print(round(cv(df.budget), 2)) print(round(cv(df.duration), 2)) 1.03 0.68
  • def cv(x):a small function (week 2): the standard deviation divided by the mean
  • cv(df.budget)48.6M ÷ 47.0M = 1.03: the spread is larger than the typical value
  • cv(df.duration)0.68: durations vary much less, relative to their mean
One statistic across regions

Consistency of project budgets by region

RegionProjectsMedian budgetCV
Region IV-B1,467₱37.6M1.18: least consistent
Region VIII1,935₱27.5M1.07
Central Office180₱144.5M1.05
Region III5,412₱46.3M0.72: most consistent
Routine applied

Six lines that describe any numeric column

These are run in order on every new column. The routine takes about a minute and replaces guesswork with description. Here col stands for any one column (for example df.budget) and threshold for a chosen cut-off number.

Plotting after the numbers

The numbers indicate what shape to expect. If the picture disagrees, one of the two is wrong and the discrepancy should be investigated.

col, threshold = df.budget, 1e8 col.isna().sum() # what is missing col.describe() # centre + spread col.skew() # which way it leans col.quantile([.05, .95]) # the realistic range (col < threshold).mean() # ECDF at a point col.hist(bins=30) # look at it
  • col, threshold = df.budget, 1e8name the column and the cut-off once; the six lines then work for any numeric column
Necessity of plots

Identical statistics, different data

"Anscombe's quartet: four datasets with the same means, the same variances and the same correlation, but four completely different shapes when plotted. The summary numbers cannot distinguish them; a plot can."
F. J. Anscombe, 1973: a well-known argument for plotting data
Output

Anscombe's quartet, plotted

import seaborn as sns # 44 rows: four datasets of 11 points quartet = sns.load_dataset("anscombe") by_set = quartet.groupby("dataset").y print(by_set.agg(["mean", "var"]).round(2)) sns.lmplot(data=quartet, x="x", y="y", col="dataset", col_wrap=2, ci=None, height=2.4, aspect=1.5) plt.show() mean var dataset I 7.5 4.13 II 7.5 4.13 III 7.5 4.12 IV 7.5 4.12
Four scatter plots in a 2 by 2 grid, each with the same straight fitted line. I: points scattered loosely around the line. II: points on a smooth curve that rises and falls. III: points on a tight straight line except one high outlier. IV: ten points stacked at x = 8 and one point alone at x = 19.

the printed table gives each dataset the same mean (7.5) and variance (4.12–4.13) of y, and the fitted lines are identical. Only the plots show a loose cloud, a curve, a line with an outlier, and a single influential point.

Glossary

Terms introduced this week

Centre and spread

EDA
exploratory data analysis: summaries and charts before testing ideas
variable (in statistics)
one measured characteristic, i.e. one column (not a Python name)
distribution
how a variable's values are spread out
mean
add the values, divide by how many
median
the middle value once sorted
mode
the most frequent value; works for categories
range
largest minus smallest
variance
average squared distance from the mean
standard deviation (SD)
square root of the variance; typical distance from the mean
percentile / quartile
value with p% below it; quartiles are p25, p50, p75
IQR
Q3 − Q1: width of the middle half
coefficient of variation (CV)
SD ÷ mean; compares spread across units
denominator
the "out of how many" behind a number

Shape and categories

skew
lopsidedness; right-skewed has a long tail of large values
kurtosis
how often extreme values appear (normal curve = 0)
normal distribution
the symmetric bell curve
histogram
bars counting values per range
bins
the equal-width ranges a histogram counts into
box plot
box Q1–Q3, median line, whiskers, outlier dots
outlier
a value far from the rest (beyond the 1.5 × IQR fence)
log transform
replace x by log₁₀(x) to re-space a skewed axis
ECDF
share of values below any chosen threshold
categorical
a column of labels, not amounts
frequency table
each category with its count or share
survivorship bias
judging only the cases that got through a filter
This week's lab

Describing, comparing and plotting

Exam scores through describe(), a tight and a skewed series to compare centres, calm-vs-wild spreads, and an income histogram whose appearance changes with the bins. About 45 minutes.

Lab tasks

describe(), mean()/median(), std() and range, and ax.hist() with labeled axes.

Optional extension

value_counts(normalize=True) for a categorical, and a boxplot related back to week 5's IQR fences.

Summary

Four main points

Readings

Preparation for next week

Next week

Data exploration II

Multivariate EDA and visualization: correlations, group comparisons, and plots that show how variables move together.

DS 227 · Knowledge Discovery in Data