NumPy arrays explained: shape, dtype, and axes in a first analysis
Learn how NumPy ndarrays differ from Python lists and labeled DataFrames. Build an array, inspect its shape and dtype, calculate along chosen axes, use broadcasting, and understand when a slice shares data.
NumPy is a core Python library for numerical arrays and calculations. Its central structure, ndarray, stores values across one or more axes, usually with a shared data type. Shape gives the size of each axis and dtype describes each element, so checking both helps you predict the form and meaning of a result.
This guide turns a small, fictional building-usage table into an array and calculates totals by building, averages by time slot, and differences from targets. The values are illustrative, not observed measurements or a performance benchmark.
How is an array different from a Python list?
A Python list is a general container that can hold objects of different kinds. A NumPy ndarray is designed for numerical work with an explicit shape and element type. Its dimensions are called axes: a one-dimensional array is a line of values, a two-dimensional array has rows and columns, and a three-dimensional array can be viewed as a stack of two-dimensional tables.
Most numerical ndarrays use one dtype for their elements. That is useful for consistent calculations, but it is different from a labeled table with columns such as order ID, region, date, and revenue. For named, potentially mixed-type columns, a DataFrame library such as pandas or Polars may express the task more clearly. NumPy is a natural fit when the work centers on regular numerical blocks and array operations.
Install NumPy and inspect an array
Install NumPy into the Python environment you intend to use. The second command should print the version available to that interpreter. If import fails afterward, check whether your terminal, notebook, and editor use the same Python environment.
python -m pip install numpy
python -c "import numpy as np; print(np.__version__)"You can create an ndarray from nested Python sequences. Inspect its dimensions, element count, and dtype instead of assuming that the nested lists were interpreted as intended.
import numpy as np
values = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64)
print(values.shape)
print(values.ndim)
print(values.size)
print(values.dtype)A shape of (2, 3) means two rows and three columns. ndim is the number of axes, and size is the product of the dimensions. dtype is not merely a display preference: it affects the value range and how arithmetic is performed. Choose a numeric type that can represent the input and expected results; narrow integer types and unsigned arithmetic can produce errors or surprising values when their range or sign matters.
Read shape as part of the data
In the next example, each row is a building and each column is one of four time slots. The numbers are fictional kWh readings created to make the calculations easy to check.
readings = np.array(
[
[10, 12, 11, 13],
[8, 9, 9, 10],
[15, 14, 16, 15],
],
dtype=np.float64,
)
print(readings.shape)The shape (3, 4) preserves three buildings and four time slots. Flattening the array into 12 values would lose that relationship unless you separately kept track of each position. Shape therefore describes the structure needed to interpret the values, not only their count.
Use axis to choose what gets combined
An axis tells a reduction which direction to combine. For a two-dimensional array, axis=0 combines down the rows and leaves one result for each column. axis=1 combines across the columns and leaves one result for each row. One useful check is that the reduced axis disappears from the result shape.
building_totals = readings.sum(axis=1)
slot_averages = readings.mean(axis=0)
threshold_mask = readings >= 12
count_at_or_above = threshold_mask.sum(axis=1)
print(building_totals)
print(slot_averages)
print(count_at_or_above)Each building total is 46, 36, and 60 because four time slots are added within each row. The per-slot averages are 11, about 11.67, 12, and about 12.67 because each column contains the readings from three buildings. The condition creates a Boolean array; summing its true values across each row counts the time slots at or above 12, giving 2, 0, and 4. These values are hand-calculated from the displayed example, not a claim that the code was run.
If an axis result seems wrong, check its length and what each position represents. A per-building result should have length 3, while a per-slot result should have length 4. Matching lengths alone do not prove that the grouping is correct, so name the result according to the question it answers.
Element-wise operations and broadcasting
Arithmetic on arrays is usually element by element. Broadcasting lets arrays with different shapes work together when dimensions, compared from the right, are equal or one of them is 1. Missing leading dimensions are treated as size 1. This can apply a short vector across rows without explicitly copying that vector, although large intermediate results can still consume substantial memory.
Suppose each time slot has a target value. Subtracting a vector of four targets from a three-by-four readings array applies each target to the matching column.
targets = np.array([10, 10, 12, 12], dtype=np.float64)
difference_from_target = readings - targets
print(difference_from_target.shape)
print(difference_from_target)The shapes are (3, 4) and (4,). Their trailing dimensions match, so the result remains (3, 4). If broadcasting fails, line up the shapes from the right and check every pair. To apply a different value to each building, a vector of length 3 needs an explicit singleton column dimension, producing shape (3, 1); then it can broadcast across four slots. Adding that dimension communicates the intended row-wise meaning as well as fixing the shape.
A slice can share data with its source
Basic NumPy slicing commonly creates a view rather than an independent data copy. A small slice can therefore refer to the same memory as the original array, and editing the slice may change the source. Call copy() when you need an independent array. This can avoid unintended edits, although creating a copy uses additional memory. Advanced indexing has different copy behavior, so consult the indexing documentation when a selection will be modified.
Troubleshoot and choose the right tool
When a result has the wrong form, print shape and ndim first. Decide whether the question asks for a result by row or by column, then compare that intent with the axis and the output length. For a broadcasting error, compare dimensions from the right. If values look wrong, inspect dtype and whether the input exceeds an integer type's range. If changing a selected slice also changes the source, check whether the selection is a view.
NumPy supports concise operations over numerical arrays, but vectorized syntax does not guarantee a speedup for every dataset or operation. Large temporary arrays may increase memory use, and tiny inputs may not benefit meaningfully. Choose based on data shape, required calculations, memory limits, and the semantics of the existing code rather than assuming one library is always fastest.
When named columns, row labels, mixed data types, joins, or table-oriented missing-value handling are central, a DataFrame may be easier to read. For regular numerical structures such as measurements, image pixels, or model inputs, ndarray is often a natural representation.
References
NumPy User Guide, Quickstart: https://numpy.org/doc/stable/user/quickstart.html
NumPy User Guide, Absolute basics for beginners: https://numpy.org/doc/stable/user/absolute_beginners.html
NumPy User Guide, Array creation: https://numpy.org/doc/stable/user/basics.creation.html
NumPy User Guide, Data types: https://numpy.org/doc/stable/user/basics.types.html
NumPy User Guide, Indexing on ndarrays: https://numpy.org/doc/stable/user/basics.indexing.html
NumPy User Guide, Broadcasting: https://numpy.org/doc/stable/user/basics.broadcasting.html
NumPy User Guide, Universal functions basics: https://numpy.org/doc/stable/user/basics.ufuncs.html
NumPy User Guide, Copies and views: https://numpy.org/doc/stable/user/basics.copies.html