Lesson 2 of 4
Create arrays in different ways, inspect their shape and type, and select values from one- and two-dimensional arrays.
About 30 minutes
np.array(), np.arange(), np.linspace(), np.zeros() and np.ones()shape, ndim, size and dtypeBesides converting lists with np.array(), NumPy can generate arrays directly. This is how you create ranges of temperatures, time steps or positions for a calculation.
| Function | Creates | Example result |
|---|---|---|
np.arange(start, stop, step) | Evenly spaced values with a given step (stop not included), like range() but allowing decimals | np.arange(0, 1, 0.25) → [0. 0.25 0.5 0.75] |
np.linspace(start, stop, n) | n evenly spaced values, including both ends | np.linspace(0, 1, 5) → [0. 0.25 0.5 0.75 1.] |
np.zeros(n) | An array of n zeros | np.zeros(3) → [0. 0. 0.] |
np.ones(n) | An array of n ones | np.ones(3) → [1. 1. 1.] |
import numpy as nptemperatures = np.arange(300, 701, 100) # 300 K to 700 K in 100 K stepsstrains = np.linspace(0, 0.02, 5) # 5 strain values from 0 to 2%results = np.zeros(4) # placeholders to fill in laterprint(temperatures)print(strains)print(results)arange or linspace?
np.arange() when you know the step size, and np.linspace() when you know how many points you want. For decimal steps linspace is safer, because rounding errors can make arange include or miss the last value unexpectedly.Every array carries information about itself in attributes, which you read with a dot but without brackets.
| Attribute | Meaning |
|---|---|
a.shape | The size along each dimension, as a tuple, e.g. (5,) or (3, 4) |
a.ndim | The number of dimensions |
a.size | The total number of elements |
a.dtype | The data type of the elements, e.g. int64 or float64 |
All elements of an array share one data type. If you mix integers and floats, NumPy converts everything to floats. This is part of why arrays are fast, but it also means an array isn't the right place for mixed data such as names and numbers together.
import numpy as npcounts = np.array([4, 2, 8])mixed = np.array([4, 2.5, 8])print(counts.dtype, counts.shape, counts.size)print(mixed.dtype)print(mixed)The exact integer type depends on the computer. Python in the browser uses int32; on most desktop computers you will see int64. Both are whole numbers; they differ in the largest value they can hold.
Experimental data often comes as a table: rows of samples and columns of properties, or rows of time steps and columns of sensors. A two-dimensional array stores such a table. Create one from a list of lists, where each inner list is a row.
import numpy as np# Rows: three samples. Columns: hardness (HV) at 4 positions.hardness = np.array([ [152, 160, 158, 149], [201, 198, 205, 199], [175, 172, 178, 176],])print(hardness)print("Shape:", hardness.shape)print("Dimensions:", hardness.ndim)The shape (3, 4) means 3 rows and 4 columns. Shapes are always listed as rows first, then columns.
One-dimensional arrays are indexed and sliced exactly like lists. For a two-dimensional array, give the row and the column separated by a comma: a[row, column]. A colon on its own means all, so a[:, 0] is the whole first column and a[1, :] (or just a[1]) is the whole second row.
import numpy as nphardness = np.array([ [152, 160, 158, 149], [201, 198, 205, 199], [175, 172, 178, 176],])print(hardness[1, 2]) # row 1, column 2print(hardness[0]) # the first sampleprint(hardness[:, 0]) # position 0 for every sampleprint(hardness[1:, :2]) # rows 1 onwards, first two columnsA table of tensile test results: one row per steel sample, one column per property.
import numpy as np# Rows: four steel samples. Columns: yield strength (MPa), tensile strength (MPa), elongation (%).tensile = np.array([ [215, 505, 40], [250, 460, 23], [350, 620, 18], [520, 760, 12],])print("Shape:", tensile.shape)print("Third sample, tensile strength:", tensile[2, 1], "MPa")print("Elongation of every sample:", tensile[:, 2])print("First two samples, strengths only:")print(tensile[:2, :2])Indices count from 0, so [2, 1] is the third row and the second column. [:2, :2] takes the first two rows and the first two columns.
You can also assign to an index or a slice to change values. Assigning a single number to a slice sets every element in it.
import numpy as npreadings = np.array([8.95, 8.97, 0.0, 8.96, 0.0])readings[2] = 8.94 # replace one valuereadings[3:] = 9.00 # set every value in a sliceprint(readings)Slices are views, not copies
.copy() if you need an independent array: part = readings[:3].copy().Choose an answer and press Check answer. You can retry as often as you like.