Artificial Intelligence / Python Libraries
Learn to organize, explore, and calculate with numerical data using NumPy arrays.
What is NumPy?
NumPy is short for Numerical Python. Pronounced “NUM-pie,” it is a Python library for working with numbers and collections of numbers. Its central feature is the array: a structure that stores values, often in one or more dimensions, so you can work with them as a group.
NumPy can perform calculations across an entire array, which makes it useful for tasks such as analyzing data, working with measurements, and building scientific or machine-learning tools. Many Python libraries use NumPy arrays to represent numerical data.
In short, NumPy gives Python efficient tools for organizing and calculating with numerical data.
What is an array in NumPy?
A NumPy array stores a group of values in an organized structure. A one-dimensional array is like a row of values. Arrays can also have multiple dimensions, such as rows and columns in a table.
1D · one dimension
Values along one direction
2D · two dimensions
Values across rows and columns
3D · three dimensions
Values across a volume
For example, this creates a one-dimensional array of test scores:
import numpy as np
scores = np.array([82, 90, 75])
Here, scores contains three numbers in one array. NumPy arrays are commonly used when you want to organize numerical data and calculate with many values together.
Examples of 2D and 3D arrays
A 2D array
A 2D array can represent a table with rows and columns. This example has two rows and three columns:
import numpy as np
two_d = np.array([
[1, 2, 3],
[4, 5, 6]
])
This array has two rows and three columns.
A 3D array
A 3D array can be pictured as a stack of 2D tables. This example has two tables, each with two rows and three columns:
import numpy as np
three_d = np.array([
[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]
])
This array has two tables, with two rows and three values in each row.
Try NumPy in your browser
Edit any example and select its Run code button. Each runner displays the value of the last line, like a notebook, so the examples do not need a print() statement. The first run loads Python and NumPy in your browser, so it may take a little while and needs an internet connection.
Run a 1D array
Output will appear here.
Run a 2D array
Output will appear here.
Run a 3D array
Output will appear here.
Calculate with an entire array at once
NumPy lets you apply one calculation to every value in an array with a single expression. For example, adding 10 to an array adds 10 to each value:
numbers = np.array([1, 2, 3])
numbers + 10
The result is [11, 12, 13]. You do not need to write a loop to update each value.
Output will appear here.
Access values in an array
Array positions are called indexes. Python starts counting indexes at 0, so index 0 selects the first value.
In a 1D array, use one index:
numbers = np.array([10, 20, 30])
numbers[0] # 10, the first value
In a 2D array, use a row index and a column index. A colon (:) means “select all” along that direction:
grid = np.array([[1, 2, 3],
[4, 5, 6]])
grid[0] # first row: [1, 2, 3]
grid[:, 1] # second column: [2, 5]
Try the selections below. The code prints the first value, the first row, and the second column.
Output will appear here.
Why should we use NumPy arrays?
Here is a simple timing comparison. The Python list uses a loop to add 1 to each number one at a time. The NumPy array adds 1 to all its numbers in one operation. The input data is prepared before timing, and the time you see depends on your device and browser.
Timing results will appear here.
NumPy is useful for numerical work because one array operation can update many values without writing a Python loop. For a small amount of data, the difference may be tiny; this example uses 100,000 values to make the timings easier to compare.
How are lists and NumPy arrays stored in memory?
A Python list stores references to Python objects. Those objects can be different kinds of values, and they may live in different places in memory. A regular NumPy array stores its numerical values together in a data buffer and keeps information such as the values’ type and the array’s dimensions alongside it.
Python list
The list points to separate Python values.
NumPy array
Numeric values are stored together with array information.
Because an array’s numeric values use one consistent data type and are arranged for numerical operations, NumPy can process many of them together efficiently. Lists are more flexible and convenient for general collections.
See the official Python list documentation and NumPy’s ndarray memory layout guide for more detail.
Select a range with slicing
Slicing selects a range of values. In numbers[1:4], the range starts at index 1 and stops before index 4, so it selects indexes 1, 2, and 3.
For a 2D array, write a slice for the rows and a slice for the columns. This selects rows 0 and 1, and columns 1 and 2:
grid[0:2, 1:3]
Run the example to see both slices:
Output will appear here.
Filter values with a condition
You can use a condition to find values that match what you are looking for. NumPy checks the condition for each value and creates a Boolean array of True and False results. Use that Boolean array inside square brackets to select the matching values.
numbers = np.array([10, 20, 30, 40, 50])
numbers[numbers > 25] # [30, 40, 50]
Try it below. The first output shows which values pass the condition; the second shows those values selected from the array.
Output will appear here.
Combine conditions
Use & when a value must match both conditions. Put parentheses around each comparison so NumPy evaluates each one before combining them.
numbers = np.array([10, 20, 30, 40, 50])
matches = (numbers > 15) & (numbers < 45)
numbers[matches] # [20, 30, 40]
Try the code below. It selects values greater than 15 and less than 45:
Output will appear here.
Change values in an array
Use an index to replace one value. You can also use a condition to replace every matching value.
numbers = np.array([10, 20, 30, 40])
numbers[1] = 99 # change the value at index 1
numbers[numbers > 25] = 0 # replace values greater than 25
Try it below and see the array after each change:
Output will appear here.
Summarize and apply math functions
NumPy can summarize values in an array with methods such as sum(), min(), max(), and mean(). These return the total, smallest value, largest value, and average.
Try these calculations on a set of test scores:
Output will appear here.
Apply math functions to every value
NumPy’s math functions also work element by element across an array. For example, np.sqrt() finds each value’s square root, and np.round() rounds each value:
Output will appear here.
Understand axis in a 2D array
The axis argument tells NumPy which direction to calculate along. In a 2D array, axis=0 works down the rows and returns one result for each column. axis=1 works across the columns and returns one result for each row.
Here, each row represents a student and each column represents a subject. The example calculates the average for each subject, then the average for each student:
Output will appear here.
Create arrays with NumPy helpers
You do not always need to type every value into an array. np.arange() creates a sequence of numbers, while np.zeros() and np.ones() create arrays filled with zeros or ones.
In np.arange(1, 6), the sequence starts at 1 and stops before 6. In these examples, dtype=int asks for whole numbers:
Output will appear here.
Inspect an array: dimensions, shape, and dtype
NumPy arrays have useful attributes that describe their data. ndim tells you the number of dimensions, shape tells you how many values are along each dimension, size counts all the values, and dtype tells you the data type stored in the array.
This example creates a 2D array of 32-bit integers and prints those details:
Output will appear here.
Reshape an array
reshape() rearranges an array into a different number of rows and columns. The total number of values must stay the same. Here, six values are rearranged into two rows with three values in each row:
Output will appear here.
Broadcasting: combine arrays of different dimensions
Broadcasting lets NumPy combine arrays with compatible dimensions. In this example, the 1D array has one value for each column in the 2D array, so NumPy applies those values to every row:
grid = np.array([[1, 2, 3],
[4, 5, 6]])
increments = np.array([10, 20, 30])
grid + increments
The result is [[11, 22, 33], [14, 25, 36]]. The same three increments are added across both rows.
Output will appear here.
Combine arrays with concatenate
np.concatenate() joins arrays. For 1D arrays, it places the values from the second array after the values from the first. For 2D arrays, you can join rows along axis=0; the arrays need the same number of columns.
Run these examples to join two 1D arrays, then add rows to a 2D array:
Output will appear here.
Create random arrays
NumPy’s default_rng() creates a random number generator. Here, it makes five simulated dice rolls. The seed makes the same sequence appear each time you run the example; remove the seed to get a different sequence.
Output will appear here.
high=7 is excluded from the possible results, so this generates values from 1 through 6. See NumPy’s random generator documentation.
Save and load arrays
Use np.save() and np.load() to store an array in NumPy’s .npy format, which preserves its data type and dimensions. Use np.savetxt() and np.loadtxt() for readable text files such as CSV.
This example saves and loads the same numbers in both formats:
Output will appear here.
The playground stores these files in a temporary browser environment, not on the visitor’s computer. In a local Python project, the same code reads and writes files in the folder where Python is running. See NumPy’s file I/O guide.
Sort and find unique values
np.sort() returns the values in sorted order. np.unique() returns the distinct values, sorted by default. These are useful when you want to organize data or see which values appear in it.
Output will appear here.
Convert an array’s data type
Use astype() to make a converted array with a different data type. For example, converting integers to floating-point numbers lets the values represent decimals. The original array keeps its original type.
Output will appear here.
Matrix multiplication: * vs @
For NumPy arrays, * multiplies values in matching positions. The @ operator performs matrix multiplication: it combines each row of the first matrix with each column of the second. For the multiplication to work, the number of columns in the first matrix must match the number of rows in the second.
Run both operations on the same two matrices to compare their results:
Output will appear here.
Copies and views
A basic slice of a NumPy array is usually a view: it looks at the same data as the original array. Changing a value through the view also changes the original. Use .copy() when you want a separate array whose values can be changed independently.
Run this example to see both behaviors:
Output will appear here.
In this example, the view shares its original array’s data, while the copied slice has its own data. See NumPy’s copies and views guide.
Put it all together
Use this 2D array of student scores to calculate each student’s average, select scores of 75 or higher, and find the highest score. Each row represents one student.
Output will appear here.
To practice, change the scores or passing threshold, then try finding the lowest score with scores.min().