NumPy explained: arrays, vectorisation and why they are fast

TL;DR

Difficulty: Intermediate

NumPy does arithmetic on whole columns at once. Three promises matter more than its speed:

  • One type per array: small, fast, and a stray text value shows up as an object dtype instead of hiding.
  • Whole columns, not rows: say the rule "for all orders" and it becomes one line you can check.
  • A seeded Generator (np.random.default_rng) makes every simulated number repeatable, together with the NumPy version. Traps: slices are views that change your original, NaN spreads through sums, refunds hide as negative rows, and looping over an array is slower than looping over a list.

Every Python tool for data analysis, pandas included, stands on NumPy. This chapter explains what it is and why it is fast, then builds a year of an online shop's orders from seeded random numbers and answers a real pricing question in a few vectorised lines. Every block runs, and every output shown is real.

If you only read one section

NumPy is the part of Python that does arithmetic on whole columns of numbers at once. Almost every data tool you will meet in Python, pandas included, is built on top of it. You do not need to love it, but you need to understand three of its promises, because each one changes how trustworthy an analysis is.

  • One type per array. A NumPy array holds numbers of a single kind, stored side by side in memory. That is why it is small and fast, and it is also why a stray text value in your order export shows up as a problem instead of hiding in a cell.
  • Whole columns, not rows. You write "margin is 52% of order value" once, and NumPy applies it to every order. The code reads like the business rule, which makes it easier to check than a loop or a dragged down spreadsheet formula.
  • A seed for every random number. Simulations, samples and test data come from a generator you start with a fixed seed. Anyone can rerun the analysis and get the same numbers, which makes a result something you can audit rather than something you have to believe.

For the person who commissions this kind of work, the practical test is simple. Ask the analyst two questions: "If I run this again next week, do I get the same numbers?" and "Where in the code is the business rule written down?" Good NumPy work answers both in one line each. The speed, which tutorials love to lead with, is the least important of the three for most businesses. In the example below a loop over a year of orders takes about three thousandths of a second. Speed matters when the data or the number of scenarios gets large. Clarity and repeatability matter every single time.

The short answer: say it for all orders at once

Here is the reader's question, in full: what is NumPy, why is it so much faster than plain Python, and what do I need to know about it as an analyst?

The one idea that carries this chapter is a habit of thought, not a function. When you catch yourself thinking "for each order, do this", stop and rephrase it as "for all orders, this". The first sentence becomes a loop. The second becomes one line of NumPy. Almost every operation an analyst needs (a margin, a filter, a discount rule, a share, a percentile, a scenario) can be said the second way.

I call it the "for all orders" test. If you can say the rule for all rows at once, NumPy can do it at once. If you genuinely cannot (each step depends on the result of the previous one, like a running stock level that triggers a reorder), a loop is honest and fine, and the flow chart near the end of this chapter shows how to decide.

Example: Fernhill Home's question, said two ways

The example business throughout this series is invented: Fernhill Home, an online homeware shop in York selling candles, ceramics and textiles. Grace founded it, Tariq is the analyst. It takes about 48,000 orders a year from about 21,000 customers, the average order value is £58, and the gross margin is 52%.

Grace asks Tariq: "If we gave 10% off every order of £75 or more, what would it cost us in margin?"

Said the loop way: take the first order. Work out 52% of its value. If the order is £75 or more, take off 10% of its value. Add the result to a running total. Move to the next order. Repeat 47,948 times.

Said the "for all orders" way: margin is 52% of every order value, minus 10% of the value where the value is at least £75. Add it up.

margin = order_values * 0.52 - np.where(order_values >= 75, order_values * 0.10, 0.0)
margin.sum()

That is the whole calculation. By the end of this chapter you will have generated order_values yourself, understood every piece of that line, and seen how long each version takes on a real laptop.

Setting up: the versions this chapter uses

Everything here runs in a notebook or a script. If you have not set one up yet, the first chapter of this series, why Python for data analysis and how to set it up, walks through it, and the second, the Python basics an analyst actually needs, covers lists, loops and functions, which this chapter builds on.

As I write this in early July 2025, the current releases are Python 3.13 (released 7 October 2024) and NumPy 2.3 (2.3.0 on 7 June 2025, 2.3.1 on 21 June 2025)12. NumPy 2.3 supports Python 3.11 to 3.133. I ran every block in this chapter with Python 3.13.3 and NumPy 2.3.1, and the outputs shown are the real ones.

python -m pip install "numpy>=2.3"
import sys
import numpy as np

print(sys.version.split()[0], np.__version__)
# 3.13.3 2.3.1

The standard reference for this chapter is Wes McKinney's Python for Data Analysis, chapter 4, "NumPy Basics: Arrays and Vectorized Computation"4. The book was written against NumPy 1.x. The ideas carry over unchanged, but NumPy 2.0 (June 2024) removed a handful of old names, so where an older example writes np.NaN you now write np.nan, and np.string_ became np.bytes_5. I use the current names throughout.

What an array is, and why one type matters

A Python list is a row of boxes, and each box holds a pointer to an object somewhere else in memory. The objects can be anything: a number, a piece of text, None, another list. That flexibility is lovely for general programming and expensive for arithmetic, because before Python can add two values it has to look up what kind of thing each one is.

A NumPy array, the ndarray, is different. It is one block of memory holding values of a single type, its dtype (data type), stored side by side4. Because every value has the same type and size, NumPy's compiled code can run through the block without asking any questions. That is the whole secret of the speed, and it is also a discipline: an array cannot quietly hold a number in one row and a word in the next.

Example: 48,000 order values in a list and in an array

Tariq has a year of order values. Here they are as a list and as an array, with the memory each one takes.

import sys
import numpy as np

order_values_list = [58.0] * 48_000              # 48,000 order values in a plain list
order_values_arr = np.array(order_values_list)    # the same numbers as an array

# A list stores a pointer per value plus a full Python object per value
list_bytes = sys.getsizeof(order_values_list) + sum(sys.getsizeof(v) for v in order_values_list)
print(list_bytes)                  # 1536056

print(order_values_arr.dtype)      # float64
print(order_values_arr.itemsize)   # 8, bytes per value
print(order_values_arr.nbytes)     # 384000

The list needs about 1.5 MB, the array 384 KB: a quarter of the memory for the same 48,000 numbers. Each value in the array is a float64, a 64 bit floating point number taking exactly 8 bytes. In the list each value is a Python object of 24 bytes plus an 8 byte pointer to it.

The dtype is a check, not a detail

The type matters for more than memory. Watch what happens when one messy value gets into the data.

pence = np.array([5800, 1299, 4550])    # prices in whole pence
print(pence.dtype, pence.sum())         # int64 11649

messy = np.array([58, "58.00", None])   # one number, one text, one missing
print(messy.dtype)                      # object

Clean whole numbers become int64. The messy column becomes object, which means NumPy has given up and gone back to storing Python objects. Arithmetic on it is slow, and some of it will fail. When you load real exports in the chapter on loading business data, an object column where you expected numbers is the first warning sign of a currency symbol, a thousands separator or a "N/A" somewhere in the file. The dtype is the quickest data quality check you will ever run.

Two practical notes. First, money: chapter 2 showed why 0.1 + 0.2 is not exactly 0.3. For totals and reports, floats rounded to pennies at the end are fine. For anything that must reconcile to the penny with accounting, store whole pence as integers, as in pence above. Second, since NumPy 2.0 the default integer is 64 bit on every 64 bit system, Windows included5. Older code sometimes overflowed on Windows when it summed large integer columns. On current NumPy that trap is gone.

Seeded random numbers: the receipt for every example

Every chapter of this series starts by generating its example data, so that you can run every line without a file from me. That only works if the "random" numbers are the same on your machine as on mine. NumPy's random numbers are pseudorandom: an algorithm produces them deterministically from a starting value, the seed. Same seed, same numbers.

The modern way to get them is a Generator created with np.random.default_rng(seed). The NumPy documentation names default_rng as the recommended constructor6. Much of the code you will inherit uses the older style, np.random.seed(42) followed by np.random.normal(...). That still runs, but it relies on one hidden global state shared by everything in your session, so a library that draws a random number somewhere else silently changes your results. A generator you hold in a variable has no such leak.

One honest limit, which tutorials rarely mention: NumPy promises the same stream from the same seed on the same NumPy build and the same machine, and it reserves the right to improve its algorithms between versions7. So a seed is a receipt only together with the version. That is why I print np.__version__ at the top. In a real project, pin the version in your requirements file. The chapter on a reproducible workflow comes back to this.

Example: a year of Fernhill's daily orders

Tariq wants a realistic year of daily order counts to practise on: about 48,000 orders, more on Mondays and Sundays than on Saturdays, and gentle growth of about 8% across the year.

Counts of independent events in a fixed period, such as orders per day, are classically modelled with the Poisson distribution: you give it the expected count, it returns whole numbers that scatter around it. First, the calendar and the weekday.

rng = np.random.default_rng(seed=2025)   # the receipt: same seed, same data

# One value per day, 1 July 2024 to 30 June 2025 (the end is excluded)
days = np.arange("2024-07-01", "2025-07-01", dtype="datetime64[D]")
print(len(days), days[0], days[-1])      # 365 2024-07-01 2025-06-30

# datetime64 counts days from 1 January 1970, which was a Thursday.
# Adding 3 and taking the remainder after 7 gives Monday = 0 ... Sunday = 6
weekday = (days.astype("int64") + 3) % 7
print(weekday[:7])                       # [0 1 2 3 4 5 6], 1 July 2024 was a Monday

Now the expected orders per day: a base level of 48,000 / 365, multiplied by a weekday factor and a growth trend.

# How busy each weekday is relative to an average day (Monday first)
weekday_factor = np.array([1.15, 1.05, 1.00, 0.98, 0.90, 0.85, 1.07])
weekday_factor = weekday_factor / weekday_factor.mean()   # rescale so the average is 1

t = np.arange(len(days))                                  # 0, 1, 2, ... 364
trend = 1 + 0.08 * (t / (len(days) - 1) - 0.5)            # 4% below average in July, 4% above in June

expected = 48_000 / 365 * weekday_factor[weekday] * trend # expected orders for every day
daily_orders = rng.poisson(expected)                      # one random count per day

print(daily_orders[:7])                                   # [158 174 120 130 110  96 112]
print(daily_orders.sum(), daily_orders.min(), daily_orders.max())   # 47948 90 182

Look at weekday_factor[weekday]. weekday is an array of 365 numbers between 0 and 6, and using it as an index picks the matching factor for every day at once: 365 lookups, no loop. The year comes out at 47,948 orders, close to the 48,000 we aimed for, which is exactly what random variation looks like.

The time zone trap in weekday counts

datetime64 has no notion of time zones. The NumPy documentation calls it "naive" time8. Fernhill's shop export records order times in UTC (Coordinated Universal Time), while the business, and GA4, think in Europe/London time. In summer, an order placed at 11.30pm on a Sunday in York is stamped 10.30pm UTC, still Sunday. But a Monday 12.30am order is stamped 11.30pm on Sunday in UTC, so it is counted on the wrong day. Weekday and hour of day charts built straight from UTC timestamps quietly move late evening orders. Convert to the local time zone first, which pandas does well and which the chapter on time series covers. NumPy alone cannot.

Reshaping and aggregating along an axis

An array can have more than one dimension. A two dimensional array is a table of rows and columns, and that opens up a very useful trick: arrange the data so that the question you want to ask runs along one axis, then aggregate along it.

axis=0 means "collapse the rows", giving one result per column. axis=1 means "collapse the columns", giving one result per row. If that feels backwards at first, everyone has the same moment. Say it as "the axis you name is the one that disappears".

Example: orders by weekday and by week

Because 1 July 2024 was a Monday, the first 364 days are exactly 52 full weeks. Reshape them into a table of 52 rows (weeks) and seven columns (Monday to Sunday).

weeks = daily_orders[:364].reshape(52, 7)    # 52 weeks, Monday ... Sunday
print(weeks.shape)                           # (52, 7)

# axis=0 collapses the 52 weeks: the average Monday, the average Tuesday ...
print(weeks.mean(axis=0).round(1))
# [152.7 138.6 132.8 127.2 118.8 110.5 138.7]

# axis=1 collapses the seven days: one total per week
weekly_totals = weeks.sum(axis=1)
print(weekly_totals[:4], weekly_totals.min(), weekly_totals.max())
# [900 848 927 890] 846 1044

The average Monday brings about 153 orders, the average Saturday about 111. Weekly totals run from 846 to 1,044. Note that the reshape did not copy anything: it is a different view onto the same 364 numbers, which matters later in this chapter.

Average simulated orders per day by weekday over 52 weeks from July 2024 to June 2025: Monday 152.7, Tuesday 138.6, Wednesday 132.8, Thursday 127.2, Friday 118.8, Saturday 110.5, Sunday 138.7. Tap or click to enlarge

If you want to chart this yourself, a weekday comparison is a simple amounts chart, and the article on showing amounts and proportions with bars and dots explains why plain bars starting at zero are the right choice here.

Order values: why the average order is not the typical order

Order values are not spread evenly around the average. Most orders are modest, a few are large (a dinner service, a set of linen for a whole house), and there is no such thing as a negative order. A common model for values like this is the lognormal distribution: the logarithm of the value is normally distributed. It gives a long tail to the right, exactly the shape of real basket values.

The lognormal has one catch that confuses everyone once. NumPy's rng.lognormal(mean, sigma) takes the mean and the standard deviation of the underlying normal distribution, of the logarithm, not of the order values themselves9. To get an average order of £58 you have to work backwards. Here is the maths, and the basics of means and medians are in Foundations: mean and Foundations: median and mode.

E[X]=eμ+σ2/2,median⁡(X)=eμ,qp=eμ+zpσ\mathbb{E}[X] = e^{\mu + \sigma^2/2}, \qquad \operatorname{median}(X) = e^{\mu}, \qquad q_p = e^{\mu + z_p \sigma}

where XX is the value of one order in pounds, E[X]\mathbb{E}[X] its expected value (the long run average), μ\mu and σ\sigma the mean and standard deviation of ln⁡X\ln X, qpq_p the pp percentile of order values, and zpz_p the matching percentile of the standard normal distribution (z0.9=1.2816z_{0.9} = 1.2816 for the 90th percentile).

Step by step for Fernhill. Choose a spread of σ=0.6\sigma = 0.6, a plausible value for basket sizes. Solve the first formula for μ\mu:

μ=ln⁡(58)−σ22=4.0604−0.362=3.8804\mu = \ln(58) - \frac{\sigma^2}{2} = 4.0604 - \frac{0.36}{2} = 3.8804

where ln⁡(58)=4.0604\ln(58) = 4.0604 is the natural logarithm of the target average of £58 and σ2=0.36\sigma^2 = 0.36 is the variance of the logarithm.

Then the median is e3.8804=£48.45e^{3.8804} = £48.45, and the 90th percentile is e3.8804+1.2816×0.6=e4.6494=£104.52e^{3.8804 + 1.2816 \times 0.6} = e^{4.6494} = £104.52. So with an average order of £58, the typical order, the one in the middle, is under £50.

Example: simulating 47,948 order values

sigma = 0.6
mu = np.log(58) - sigma**2 / 2           # work back from the £58 average
print(round(mu, 4), round(np.exp(mu), 2))   # 3.8804 48.45

n_orders = daily_orders.sum()             # one value for each simulated order
order_values = rng.lognormal(mean=mu, sigma=sigma, size=n_orders).round(2)
print(order_values[:5])                   # [50.14 35.68 64.37 57.99 27.22]

print(order_values.mean().round(2), np.median(order_values).round(2))
# 57.94 48.41

print(np.percentile(order_values, [10, 25, 50, 75, 90, 99]).round(2))
# [ 22.38  32.46  48.41  72.84 104.12 192.85]

# What share of orders is below the average order value?
print((order_values < order_values.mean()).mean().round(3))   # 0.617

The simulation lands where the maths said it would: an average of £57.94 against £58 in theory, a median of £48.41 against £48.45, a 90th percentile of £104.12 against £104.52. np.percentile uses linear interpolation between the two nearest values by default10, which is the same rule as a spreadsheet's PERCENTILE.INC function.

The last line is the one I would put in front of Grace. 61.7% of orders are below the average order value. The line (order_values < order_values.mean()).mean() is worth reading slowly: the comparison produces an array of True and False, and the mean of that array is the share of True values, because True counts as 1 and False as 0. It is the shortest way to ask "what share of orders ...?" in NumPy, and you will use it constantly.

What this means for the business: a free delivery threshold, a bundle offer or a "spend £X" promotion set relative to the average order misses most customers, because most customers sit below the average. Set thresholds from the percentiles. The article on statistical thinking for growth and why averages mislead makes the general case, and showing distributions with histograms, box plots and density shows how to put this shape on a chart.

Vectorised operations: whole columns at once

Vectorisation means writing an operation once for a whole array instead of once per element. Arithmetic (+, -, *, /), comparisons (>, ==), and the many maths functions NumPy calls universal functions (np.log, np.exp, np.round) all work element by element on whole arrays, and the looping happens in compiled code4.

Example: revenue per day without a loop

Tariq has one array with a value per order and wants revenue per day. The plain Python way would loop through the orders and add each value to its day's total. The NumPy way uses two functions: np.repeat to note which day each order belongs to, and np.bincount to add up values by day.

revenue = order_values.sum()
print(revenue.round(2))                                  # 2777941.18

# Day number for every order: day 0 repeated 158 times, day 1 repeated 174 times ...
order_day = np.repeat(np.arange(len(days)), daily_orders)
print(order_day[:5], order_day.shape)                    # [0 0 0 0 0] (47948,)

# Add up order values by day number
daily_revenue = np.bincount(order_day, weights=order_values, minlength=len(days))
print(daily_revenue[:3].round(2))                        # [8352.54 9516.05 6155.06]

print(days[daily_revenue.argmax()], daily_revenue.max().round(2))
# 2025-05-19 10736.35

The year's revenue is £2,777,941.18, the best day was Monday 19 May 2025 with £10,736.35, and nothing in that block loops in Python. argmax returns the position of the largest value, and using that position on days gives its date. This "position in one array, look it up in another" pattern is how NumPy keeps related arrays in step, and it is exactly what pandas will automate for you in the next chapter with an index.

Boolean masks: filtering without a loop

A comparison on an array gives an array of True and False of the same length, called a boolean mask. Use the mask inside square brackets and you get only the rows where it is True. Use it with np.where(mask, a, b) and you get a where the mask is true and b elsewhere. Those two moves replace most if statements in analysis code.

Example: the orders a £75 discount would touch

big = order_values >= 75                  # True for every order of £75 or more
print(big[:5])                            # [False False False False False]
print(big.sum(), big.mean().round(3))     # 11236 0.234
print((order_values[big].sum() / revenue).round(3))   # 0.449, share of revenue

gross_margin = order_values * 0.52                       # margin on every order
discount = np.where(big, order_values * 0.10, 0.0)       # 10% off, only where big
print(gross_margin.sum().round(2))                       # 1444529.41
print(discount.sum().round(2))                           # 124817.36
print((gross_margin - discount).sum().round(2))          # 1319712.05

So 11,236 orders, 23.4% of them, are £75 or more, and they bring in 44.9% of revenue. A 10% discount on those orders would cost £124,817 of the £1,444,529 gross margin, leaving £1,319,712. That is the answer to Grace's question from the start of the chapter, in three lines.

One warning about real exports. Fernhill's order export lists refunds as separate rows with negative values and includes test and staff orders. A mask is also how you clean that: order_values[order_values > 0] drops refund rows before you compute percentiles. Decide deliberately, though. For revenue you want refunds netted off, for the shape of basket values you do not want them at all. The chapter on cleaning data comes back to this.

Broadcasting: many scenarios in one line

Broadcasting is NumPy's rule for doing arithmetic on arrays of different shapes. NumPy compares the shapes from the last dimension backwards, and two dimensions fit when they are equal or when one of them is 1. A dimension of length 1 is stretched to match the other, without copying any data11. McKinney's appendix on advanced NumPy covers the rule in depth12.

That sounds abstract, so here is the business version: a column of scenarios times a row of orders gives a table with one row per scenario. That is how you turn one calculation into a whole set of options for a decision.

Example: four discount levels at once

Grace wants to see 0%, 5%, 10% and 15% off orders of £75 or more side by side.

levels = np.array([0.0, 0.05, 0.10, 0.15])    # shape (4,)

# levels[:, np.newaxis] has shape (4, 1): four rows, one column.
# order_values * big has shape (47948,): one row of orders, zero where not big.
# Broadcasting stretches both to (4, 47948): one row per discount level.
discounts = levels[:, np.newaxis] * order_values * big
print(discounts.shape)                          # (4, 47948)

margin_by_level = gross_margin.sum() - discounts.sum(axis=1)
print(margin_by_level.round(0))
# [1444529. 1382121. 1319712. 1257303.]

np.newaxis inserts a dimension of length 1, turning the four levels into a column. Then one multiplication builds a table of 4 × 47,948 discount amounts, and sum(axis=1) adds each row up.

How many extra orders would pay for it

A discount is only worth it if it brings in enough extra orders to cover the margin it gives away. A first rough break even divides the margin given away by the average margin per order. The idea of comparing an extra cost with the extra return is in Foundations: marginal versus average.

Δn=Dmˉ\Delta n = \frac{D}{\bar{m}}

where Δn\Delta n is the number of extra orders needed to break even, DD the total discount given away in pounds, and mˉ\bar{m} the average gross margin per order in pounds.

For the 10% level: D=£124,817D = £124{,}817 and mˉ=£30.13\bar{m} = £30.13, so Δn=124,817/30.13=4,143\Delta n = 124{,}817 / 30.13 = 4{,}143 extra orders, or 8.6% more than the 47,948 of the year.

extra_orders_needed = discounts.sum(axis=1) / gross_margin.mean()
print(gross_margin.mean().round(2))                        # 30.13
print(extra_orders_needed.round(0))                        # [   0. 2072. 4143. 6215.]
print((extra_orders_needed / n_orders * 100).round(1))     # [ 0.   4.3  8.6 13. ]
Discount on orders of £75 or moreMargin given awayGross margin leftExtra orders to break evenExtra orders in %
0%£0£1,444,52900%
5%£62,409£1,382,1212,0724.3%
10%£124,817£1,319,7124,1438.6%
15%£187,226£1,257,3036,21513.0%

This break even is deliberately rough. It assumes the extra orders bring the average margin, while in fact some of them would be large orders carrying the discount too, and it ignores customers who would have bought at full price anyway. It is still the right first question to put to a promotion: "do we really believe this brings in 8.6% more orders?" If nobody in the room believes it, the detailed model is not needed.

Views and copies: the slice that changes your original

This is the trap that catches every analyst once. When you take a slice of an array with start:stop, NumPy does not copy the data. It gives you a view: a new array object looking at the same memory13. Change the view and you change the original. NumPy does this on purpose, because copying large arrays every time you look at part of them would be slow and wasteful4.

The rule to remember:

  • Basic slicing (a[10:20], a[:, 0], reshape) returns a view.
  • Boolean masks and lists of positions (a[a > 0], a[[1, 5, 9]]) return a copy.
  • When in doubt, np.shares_memory(a, b) tells you, and .copy() makes sure.

Example: subtracting test orders from December

Tariq learns that two test orders a day were placed during December while the checkout was being changed. He takes December out to correct it.

december = daily_orders[153:184]                # day 153 is 1 December 2024
print(days[153], days[183])                     # 2024-12-01 2024-12-31
print(np.shares_memory(december, daily_orders)) # True: a view, not a copy

print(daily_orders[153])                        # 130
december -= 2                                   # remove two test orders a day
print(daily_orders[153])                        # 128, the original changed too

If Tariq meant to correct the year, that is what he wanted. If he meant to try a "what if" on a December copy, he has just changed his year's data, and every total computed afterwards is quietly two orders a day lower in December. Here is how to undo it, and the safe way to work on a part of an array.

daily_orders[153:184] += 2                      # undo the change
print(daily_orders[153])                        # 130 again

december_safe = daily_orders[153:184].copy()    # an independent copy

busy_days = daily_orders[daily_orders > 150]    # a mask always gives a copy
print(np.shares_memory(busy_days, daily_orders))   # False

The same idea exists in pandas, where it has a long history of confusing warnings. The pandas chapter of this series explains how pandas handles it in current versions.

Missing values: NaN spreads, on purpose

NumPy marks a missing floating point value with np.nan, "not a number". It has two properties that surprise people. Any arithmetic with nan gives nan, so a single missing value turns a whole sum into nan. And nan is not equal to anything, not even itself, so x == np.nan never finds it. Use np.isnan(x) instead.

The spreading is a feature. A total that turns into nan is telling you that the data has a gap you have not decided about yet. NumPy has a family of functions that skip missing values, np.nansum, np.nanmean, np.nanpercentile and others14, but using them is a business decision, not a technical one.

Example: two orders with no captured value

In Fernhill's export, two of the first ten orders have an empty value because the payment was never captured.

export_values = order_values[:10].copy()
export_values[[2, 7]] = np.nan                  # two missing values
print(export_values)
# [50.14 35.68   nan 57.99 27.22 27.35 37.62   nan 27.34 67.6 ]

print(export_values.sum())                      # nan
print(np.nansum(export_values).round(2))        # 330.94
print(np.isnan(export_values).sum())            # 2
print(np.nanmean(export_values).round(2))       # 41.37
print(np.nan == np.nan)                         # False

np.nansum treats the gaps as zero, which is right if an uncaptured payment means no sale. np.nanmean leaves them out of the average entirely, which is right if the order happened and only its value is unknown. Two functions, two different assumptions about the business. Write down which one you made.

Refunds are the cousin of this trap. Mix 40 refund rows (negative values) into 1,000 orders and the median order value falls from £45.78 to £43.82, and the mean from £56.15 to £51.82, although no customer spent less. If a chart of "order values" looks oddly low, check for negative rows first.

How fast, really: timing a loop against a vectorised version

Now the speed claim, measured rather than repeated. Python's timeit module runs a piece of code many times and reports how long it took. Its documentation advises looking at the fastest of several repeats, because slower runs are usually caused by other software on the machine, not by the code15.

Example: Grace's discount question, three ways

import timeit

values_list = order_values.tolist()            # the same 47,948 values as a plain list

def margin_loop(values):
    total = 0.0
    for v in values:
        m = v * 0.52
        if v >= 75:
            m -= v * 0.10
        total += m
    return total

def margin_vectorised(values):
    m = values * 0.52 - np.where(values >= 75, values * 0.10, 0.0)
    return m.sum()

print(round(margin_loop(values_list), 2), round(margin_vectorised(order_values), 2))
# 1319712.05 1319712.05, the same answer both ways

for label, fn, data in [("loop over a list", margin_loop, values_list),
                        ("loop over an array", margin_loop, order_values),
                        ("vectorised", margin_vectorised, order_values)]:
    best = min(timeit.repeat(lambda: fn(data), number=20, repeat=5)) / 20
    print(f"{label}: {best * 1000:.2f} ms")
# loop over a list: 3.35 ms
# loop over an array: 23.38 ms
# vectorised: 0.08 ms

These timings were measured on my laptop (an Apple M1, Python 3.13.3, NumPy 2.3.1). Yours will differ, and the numbers moved by about 20% between my own runs. The ratios are what matter: the vectorised version was about 40 times faster than the loop over a list. McKinney reports NumPy algorithms as generally 10 to 100 times faster than pure Python4, and this lands in that range.

Time to compute the discounted margin on 47,948 simulated orders, fastest of five repeats, measured on an Apple M1 with Python 3.13.3 and NumPy 2.3.1: loop over a Python list 3.35 milliseconds, loop over a NumPy array 23.38 milliseconds, vectorised NumPy 0.08 milliseconds. Tap or click to enlarge

The surprise: a loop over an array is the worst of both worlds

The middle number is the one tutorials skip. Looping over a NumPy array in plain Python was about seven times slower than looping over a list. Every time the loop takes one element out of the array, NumPy has to wrap that raw number in a new Python object, a NumPy scalar, and arithmetic on NumPy scalars is slower than on plain Python floats. So code that has "switched to NumPy" but still loops is often slower than it was before. If you use arrays, use them whole.

When speed matters, and when it does not

Three thousandths of a second for a year of orders will never be the bottleneck in a report. Speed starts to matter in three places: event level data (a GA4 export to BigQuery holds a row for every page view, scroll and click, not one per order), simulations (a forecast run 10,000 times to get a range instead of one number) and anything inside a loop of its own (computing the same metric for every product, every day, every scenario). In those places the factor of 40 is the difference between waiting a second and going for a coffee.

Loop or vectorise: how to decide

Most of the time the "for all orders" test decides it. The flow below covers the cases where it does not.

Tap or click to enlarge

The step I never skip is the check against a loop on a handful of rows. Vectorised code is short, and short code is easy to get subtly wrong: a mask the wrong way round, an axis swapped. Ten rows done by hand, or by a slow loop, and compared with np.allclose, is insurance that costs almost nothing.

Example: checking the vectorised margin against a loop

sample = order_values[:10]
loop_result = np.array([v * 0.52 - (v * 0.10 if v >= 75 else 0.0) for v in sample])
vector_result = sample * 0.52 - np.where(sample >= 75, sample * 0.10, 0.0)
print(np.allclose(loop_result, vector_result))   # True

Linear algebra, only as far as regression needs

You do not need much linear algebra as an analyst, but one piece is worth knowing now, because every regression in the later chapters of this series rests on it. A regression explains one column of numbers (orders per day, say) by a few others (the weekday, a trend, ad spend). Written with matrices, it is one line, and the basics of reading a model like this start at Foundations: expected value.

y=Xβ+ε,β^=(X⊤X)−1X⊤yy = X\beta + \varepsilon, \qquad \hat{\beta} = (X^\top X)^{-1} X^\top y

where yy is the column of daily orders (365 values), XX the matrix of explanatory columns (one row per day), β\beta the column of coefficients we want to estimate, ε\varepsilon the part of each day's orders the model does not explain, β^\hat{\beta} the least squares estimate of β\beta, X⊤X^\top the transpose of XX (rows and columns swapped) and (X⊤X)−1(X^\top X)^{-1} the inverse of the matrix X⊤XX^\top X.

In code, @ is matrix multiplication and .T the transpose. In practice you do not invert matrices yourself. np.linalg.lstsq solves the least squares problem directly and in a numerically safer way16, and from the chapter on statistical models onwards statsmodels will do it for you, with standard errors attached.

Example: weekday effects and growth from the simulated year

Tariq builds XX from seven weekday columns (1 on that weekday, 0 otherwise, often called dummy variables) and one trend column that runs from 0 on the first day to 1 a year later. Broadcasting builds the seven weekday columns in one comparison.

# Compare each day's weekday (a column of 365) with 0..6 (a row of 7): a 365 x 7 table
X_weekday = (weekday[:, np.newaxis] == np.arange(7)).astype(float)
print(X_weekday.shape)                     # (365, 7)
print(X_weekday[:2])
# [[1. 0. 0. 0. 0. 0. 0.]
#  [0. 1. 0. 0. 0. 0. 0.]]

X = np.column_stack([X_weekday, t / 364])  # add the trend: 0 on day one, 1 after a year
beta, *_ = np.linalg.lstsq(X, daily_orders, rcond=None)
print(beta.round(2))
# [146.46 132.65 126.79 121.22 112.74 104.4  132.54  12.09]

# The textbook formula gives the same answer
beta_check = np.linalg.solve(X.T @ X, X.T @ daily_orders)
print(np.allclose(beta, beta_check))       # True

Read the result like this. At the start of the year, an average Monday brings 146.5 orders and an average Saturday 104.4, and over the year every weekday grows by about 12.1 orders. We built the data with growth of 8% on about 131.5 orders a day, which is 10.5 orders, so the estimate of 12.1 is in the right place, a little high because of random variation in one year of data. A regression on simulated data you control is the best way to learn whether a method finds what is really there.

A cheat sheet of array operations

You want toNumPyExample in this chapter
Make an arraynp.array(list), np.arange, np.zerosnp.arange("2024-07-01", "2025-07-01", dtype="datetime64[D]")
Check type and sizea.dtype, a.shape, a.nbytesfloat64, 384,000 bytes
Random data, reproduciblerng = np.random.default_rng(seed)rng.poisson, rng.lognormal
Arithmetic on every valuea * 0.52, np.log(a)gross margin per order
Filter rowsa[a >= 75]orders of £75 or more
If, then, elsenp.where(mask, x, y)discount only on large orders
Share of rows meeting a rule(a < limit).mean()61.7% below the average
Summariesa.sum(), a.mean(), np.median(a), np.percentile(a, q)revenue, median order
Along one axisa.sum(axis=0), a.mean(axis=1)average by weekday, total by week
Change shapea.reshape(52, 7)year to weeks
Many scenarioslevels[:, np.newaxis] * afour discount levels
Totals by groupnp.bincount(groups, weights=a)revenue per day
Position of the largesta.argmax()the best day
Missing valuesnp.isnan, np.nansum, np.nanmeanuncaptured payments
Independent copya.copy()December what if
Least squaresnp.linalg.lstsq(X, y)weekday effects and trend

What NumPy will not do for you

NumPy is the engine, not the dashboard. It does not know column names, so X[:, 7] is "the trend" only in your head. It does not align data by date or by customer, so two arrays that are one row out of step produce wrong numbers without an error. It has no time zones and no idea what a CSV file with a header block and a totals row is.

That is what pandas adds on top, and it is the subject of the next chapter, on pandas Series and DataFrames. Everything in this chapter carries over: a pandas column is a NumPy array with a name and an index, masks and np.where work the same way, and the "for all orders" habit is exactly what makes pandas code short. When something in pandas is slow or strange, it is usually because a loop crept back in or a dtype turned into object, and you now know how to spot both.

My view

My view: learn NumPy for the habit, not for the speed. An analyst who thinks "for all orders" writes code that states the business rule once, in a form Grace could read over Tariq's shoulder and check. That is worth more than any factor of 40. Start every analysis with a seeded generator and a printed version, so every number in a report can be reproduced, and treat an object dtype or a nan total as a message from the data, not an annoyance to suppress. Reach for loops when the logic genuinely needs them, and never loop over an array element by element.

This is also how I approach data science work for clients: the rule written once, the data generated or loaded reproducibly, and every result something the client can rerun on their own machine, with code, accounts and data that belong to them.

Conclusion

NumPy gives Python a fast, typed array and a way of thinking: say the rule for all rows at once. One type per array makes data problems visible, whole column operations make the code read like the business question, and a seeded Generator makes every simulated number repeatable. For Fernhill, a few vectorised lines simulated a year of 47,948 orders, showed that 61.7% of orders sit below the £58 average, priced four discount levels in one broadcast, and estimated weekday effects and growth with least squares. The traps to remember are slices that are views, nan that spreads, refunds hiding as negative rows and UTC timestamps that move orders to the wrong day.

If you would like to put this to work on your own shop's data, book a free workshop: you bring the question, I bring the code, and we look at your data together.

If you want your own shop's numbers turned into reproducible analysis like this, book the free workshop and we will work out the question together. The first two weeks of work are on me.

Sources

  1. 1.

    Python Software Foundation, Python 3.13.0, release date 7 October 2024, https://www.python.org/downloads/release/python-3130/

  2. 2.

    Python Package Index, numpy release history (2.3.0 on 7 June 2025, 2.3.1 on 21 June 2025), https://pypi.org/project/numpy/#history

  3. 3.

    NumPy Developers, NumPy 2.3.0 release notes, June 2025, https://numpy.org/doc/2.3/release/2.3.0-notes.html

  4. 4.

    Wes McKinney, Python for Data Analysis, 3rd edition, O'Reilly, 2022, chapter 4: NumPy Basics: Arrays and Vectorized Computation, open access edition, https://wesmckinney.com/book/numpy-basics

  5. 5.

    NumPy Developers, NumPy 2.0 migration guide (removed members, default integer on Windows, NEP 50 promotion), NumPy 2.3 manual, https://numpy.org/doc/2.3/numpy_2_0_migration_guide.html

  6. 6.

    NumPy Developers, Random sampling and numpy.random.default_rng, NumPy 2.3 manual, https://numpy.org/doc/2.3/reference/random/generator.html

  7. 7.

    NumPy Developers, Compatibility policy for numpy.random, NumPy 2.3 manual, https://numpy.org/doc/2.3/reference/random/compatibility.html

  8. 8.

    NumPy Developers, Datetimes and timedeltas, NumPy 2.3 manual, https://numpy.org/doc/2.3/reference/arrays.datetime.html

  9. 9.

    NumPy Developers, numpy.random.Generator.lognormal, NumPy 2.3 manual, https://numpy.org/doc/2.3/reference/random/generated/numpy.random.Generator.lognormal.html

  10. 10.

    NumPy Developers, numpy.percentile, NumPy 2.3 manual, https://numpy.org/doc/2.3/reference/generated/numpy.percentile.html

  11. 11.

    NumPy Developers, Broadcasting, NumPy 2.3 manual, https://numpy.org/doc/2.3/user/basics.broadcasting.html

  12. 12.

    Wes McKinney, Python for Data Analysis, 3rd edition, O'Reilly, 2022, appendix A: Advanced NumPy, open access edition, https://wesmckinney.com/book/advanced-numpy

  13. 13.

    NumPy Developers, Copies and views, NumPy 2.3 manual, https://numpy.org/doc/2.3/user/basics.copies.html

  14. 14.

    NumPy Developers, numpy.nansum, NumPy 2.3 manual, https://numpy.org/doc/2.3/reference/generated/numpy.nansum.html

  15. 15.

    Python Software Foundation, timeit: measure execution time of small code snippets, Python 3.13 documentation, https://docs.python.org/3.13/library/timeit.html

  16. 16.

    NumPy Developers, numpy.linalg.lstsq, NumPy 2.3 manual, https://numpy.org/doc/2.3/reference/generated/numpy.linalg.lstsq.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter