NumPy Basics

NumPy Basics

1NumPy Basics: overview

NumPy is a library that stores numbers in an array — a grid of values that all share one type — and lets you do maths on the whole array at once instead of looping over each number.

GoalBy the end you can create 1-D and 2-D arrays, check their shape and dtype, do arithmetic on whole arrays, filter values with boolean masks, and summarise data with mean, sum and max along an axis.

Before this lesson: Python for Loops, Python Lists, Python Modules and Imports

2NumPy Basics: diagram

NumPy BasicsPython list: loopprices = [10, 20, 30]with_tax = []for p in prices: with_tax.append(p * 1.2)NumPy array: one lineprices = np.array([10, 20, 30])with_tax = prices * 1.2# [12. 24. 36.]vectorise
With a list you repeat the calculation for each item yourself. With a NumPy array you write the calculation once and it is applied to every element — shorter code that also runs much faster on big data.

3NumPy Basics: explained step by step

NumPy (short for Numerical Python) gives Python a new kind of container: the array. An array looks like a list of numbers, but it follows two strict rules: every value has the same type, and its size is fixed when it is created. Those rules let NumPy pack the numbers tightly in memory and run maths on them in fast, compiled code instead of a slow Python loop.

By convention you import it under the short name np:

import numpy as np

Creating an array and describing it

Pass a list to np.array(). Three attributes tell you what you are holding: shape (the length of each dimension), size (how many values in total) and dtype (the type shared by every value).

Python
import numpy as np

prices = np.array([4.5, 2.0, 7.5, 3.0])
print(prices)
print(prices.shape, prices.size, prices.dtype)
print(np.arange(0, 10, 2))

float64 means 64-bit decimal numbers. Whole numbers get an integer dtype such as int64 on most computers, but int32 in this browser, so do not rely on the exact integer name. Notice also that NumPy prints arrays without commas.

Vectorised maths: no loop needed

To double every price in a list you would write a loop. With an array you write the maths once and NumPy applies it to every element. This is called vectorisation. Two arrays of the same shape combine element by element: a + b adds the first values together, then the second values, and so on.

Boolean masks

A comparison such as prices <= 3 does not give one True or False. It gives a whole array of booleans, one per value. Put that mask inside square brackets and you get back only the values where the mask is True:

Python
import numpy as np

prices = np.array([4.5, 2.0, 7.5, 3.0])
print(prices * 2)
cheap = prices <= 3
print(cheap)
print(prices[cheap])
print("Average:", prices.mean())

To combine conditions, use & (and) or | (or) and wrap each comparison in parentheses: (prices > 2) & (prices < 5).

2-D arrays and axis

Nest lists to build a table of rows and columns. Summary methods such as sum(), mean() and max() squash the whole array into one number by default. Add axis=0 to work down the columns (one result per column) or axis=1 to work across the rows (one result per row). A handy way to remember it: the axis you name is the one that disappears.

Quick reference: NumPy Basics

  • Python NumPy Cheat Sheet — NumPy stores numbers in fixed-type arrays and applies operations to every element at once: build with `np.arr…

4NumPy Basics: syntax

import numpy as np

arr = np.array([1.5, 2.0, 3.5])   # array from a list
arr.shape, arr.size, arr.dtype    # describe it
arr * 2, arr + other_arr          # element-by-element maths
arr[arr > 2]                      # boolean mask: keep matches
arr.sum(), arr.mean(), arr.max()  # summaries

grid = np.array([[1, 2], [3, 4]]) # 2-D: rows x columns
grid.sum(axis=0)                  # one result per column
grid.sum(axis=1)                  # one result per row

5NumPy Basics: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
import numpy as np

# Daily high temperatures for one week, in °C
temps = np.array([18.5, 21.0, 24.5, 19.0, 26.5, 24.0, 20.5])
print("Shape:", temps.shape, "| dtype:", temps.dtype)

fahrenheit = temps * 9 / 5 + 32
print("Fahrenheit:", fahrenheit)
print("Mean:", temps.mean(), "| Max:", temps.max())

warm = temps > 22
print("Warm mask:", warm)
print("Warm days:", temps[warm], "| count:", warm.sum())

# Two cities (rows) x four days (columns)
cities = np.array([[12, 15, 11, 14],
                   [25, 27, 26, 30]])
print("Shape:", cities.shape)
print("Mean per city:", cities.mean(axis=1))
print("Max per day:", cities.max(axis=0))
Expected outputShape: (7,) | dtype: float64
Fahrenheit: [65.3 69.8 76.1 66.2 79.7 75.2 68.9]
Mean: 22.0 | Max: 26.5
Warm mask: [False False  True False  True  True False]
Warm days: [24.5 26.5 24. ] | count: 3
Shape: (2, 4)
Mean per city: [13. 27.]
Max per day: [25 27 26 30]

7NumPy Basics: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1Import NumPy under its usual short name np.
  2. Line 3-4np.array() turns a list of seven temperatures into an array.
  3. Line 5shape is (7,): one dimension holding 7 values. dtype is float64 because every value is a decimal number.
  4. Line 7-8temps * 9 / 5 + 32 converts all seven values in one expression — no loop. The result is a new array; NumPy prints it without commas.
  5. Line 9mean() and max() summarise the whole array into single numbers.
  6. Line 11-12temps > 22 compares every value and returns a boolean array — a mask with True where the day was warm.
  7. Line 13temps[warm] keeps only the values where the mask is True (24. is NumPy's short form of 24.0). warm.sum() counts the True values, because True counts as 1.
  8. Line 15-17Nested lists make a 2-D array: each inner list is a row (a city) and each position is a column (a day).
  9. Line 18shape (2, 4) means 2 rows and 4 columns.
  10. Line 19mean(axis=1) works across each row, giving one average per city.
  11. Line 20max(axis=0) works down each column, giving the highest temperature on each day.

8NumPy Basics: common mistakes

Doing maths on a list instead of an array

✗ Wrong

prices = [10, 20, 30]
print(prices * 2)
Prints [10, 20, 30, 10, 20, 30] — the list is repeated, not doubled

✓ Right

import numpy as np
prices = np.array([10, 20, 30])
print(prices * 2)

On a plain list, * means repeat. Convert the data with np.array() first; then arithmetic applies to each value.

Combining masks with and / or

✗ Wrong

import numpy as np
temps = np.array([12, 18, 25, 31])
print(temps[(temps > 15) and (temps < 30)])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

✓ Right

import numpy as np
temps = np.array([12, 18, 25, 31])
print(temps[(temps > 15) & (temps < 30)])

and and or need a single True/False, but a mask holds many. Use & and | instead, and keep the parentheses around each comparison.

Mixing up axis=0 and axis=1

✗ Wrong

import numpy as np
# rows = students, columns = tests
scores = np.array([[70, 80, 90],
                   [60, 65, 70]])
print("Per student:", scores.mean(axis=0))
Prints [65. 72.5 80. ] — three numbers (one per test) instead of two (one per student)

✓ Right

import numpy as np
scores = np.array([[70, 80, 90],
                   [60, 65, 70]])
print("Per student:", scores.mean(axis=1))

axis=0 squashes the rows and leaves one result per column. For one result per row, use axis=1.

9NumPy Basics: exercises

Write your answer, then press Check. The checks run in your browser.

1. Convert a whole array

Write code Easy

Write a function to_fahrenheit(celsius) that takes a NumPy array of Celsius temperatures and returns a new NumPy array in Fahrenheit, using F = C * 9 / 5 + 32. Do it without a loop — let NumPy apply the formula to every value.

Your code
import numpy as np

week = np.array([10.0, 15.5, 20.0, 25.0])

def to_fahrenheit(celsius):
    # return a new array (no loop needed)
    pass

print(to_fahrenheit(week))

2. Predict the array results

Predict the output Easy

Read the code and type exactly what it prints. Remember that NumPy prints arrays with spaces instead of commas.

Read this code
import numpy as np

nums = np.array([6, 9, 5, 7, 8])
print(nums * 2)
print(nums[nums > 6])
print((nums > 6).sum())
print(nums.mean())

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

What is the difference between a NumPy array and a Python list?

A list can hold mixed types and grow or shrink easily, but doing maths on it needs a loop. An array holds a single type with a fixed size, and supports element-by-element maths and fast summaries. Use lists for general collections and arrays for numeric data.

Why does my integer array show int32 here but int64 on my computer?

The default integer size depends on the platform. Python in this browser is a 32-bit build, so NumPy picks int32; most desktop computers pick int64. Your code behaves the same for everyday numbers. Pass dtype=np.int64 when you need a fixed size.

What do axis=0 and axis=1 mean?

For a 2-D array, axis=0 runs down the rows, so you get one result per column; axis=1 runs across the columns, so you get one result per row. Leave axis out to summarise the whole array into a single value.

Further reading

10Next lesson

Up nextNumPy Indexing and SlicingNumPy indexing is how you pick values out of an array: by position and slice (arr[row, col]), by a True/False mask, or …

Related:
NumPy Indexing and SlicingNumPy Math and BroadcastingPandas BasicsMatplotlib Basics

← Python pip and Virtual Environments · All Data Analysis lessons · Practise in the IDE