NumPy Creating Arrays
There are many ways to create a NumPy array, from a list or with built-in helper functions.
From a List or Tuple
Pass a list (or tuple) to np.array():
Example
import numpy as np
a = np.array([10, 20, 30])
b = np.array((1.5, 2.5, 3.5))
print(a)
print(b)[10 20 30] [1.5 2.5 3.5]
Dimensions
The number of dimensions tells you how many "levels" of nesting an array has.
| Dimensions | Looks like | Example |
|---|---|---|
| 0-D | A single number | np.array(42) |
| 1-D | A row of numbers | daily temperatures of one week |
| 2-D | A table with rows and columns | marks of students in subjects |
| 3-D | Several tables stacked | marks of students, per subject, per term |
Example
import numpy as np
zero_d = np.array(42)
one_d = np.array([1, 2, 3])
two_d = np.array([[1, 2, 3], [4, 5, 6]])
three_d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(zero_d.ndim, one_d.ndim, two_d.ndim, three_d.ndim)
print(two_d)0 1 2 3 [[1 2 3] [4 5 6]]
The ndim attribute gives the number of dimensions.
Every row of a 2-D array must have the same length. np.array([[1, 2], [3]]) raises an error, because NumPy needs a proper rectangle.
A 2-D Example: Marks Table
Example
import numpy as np
# rows = students, columns = Maths, English, Science
marks = np.array([
[85, 72, 90],
[60, 88, 75],
[92, 95, 89]
])
print(marks)
print("Shape:", marks.shape)[[85 72 90] [60 88 75] [92 95 89]] Shape: (3, 3)
Helper Functions
You often need an array before you have the data. NumPy has functions for that:
Example
import numpy as np
print(np.zeros(4))
print(np.ones((2, 3)))
print(np.full(3, 7))
print(np.eye(3))[0. 0. 0. 0.] [[1. 1. 1.] [1. 1. 1.]] [7 7 7] [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
Ranges of Numbers
np.arange() works like Python's range(), but returns an array. np.linspace() gives a fixed count of evenly spaced numbers between two values.
Example
import numpy as np
print(np.arange(5))
print(np.arange(2, 20, 4))
print(np.linspace(0, 1, 5))
print(np.linspace(0, 100, 3))[0 1 2 3 4] [ 2 6 10 14 18] [0. 0.25 0.5 0.75 1. ] [ 0. 50. 100.]
| Function | What it makes |
|---|---|
np.array(list) | Array from your data |
np.zeros(shape) | All zeros |
np.ones(shape) | All ones |
np.full(shape, value) | All the same value |
np.eye(n) | Identity matrix (1s on the diagonal) |
np.arange(start, stop, step) | Numbers with a fixed step |
np.linspace(start, stop, num) | A fixed number of evenly spaced values |
arange does not include the stop value, but linspace does include it by default.
Exercise
Exercise
What is the ndim of np.array([[1, 2], [3, 4], [5, 6]])?
