import numpy as np
NumPy
NumPy is a powerful linear algebra library for Python. What makes it so important is that almost all of the libraries in the PyData ecosystem (pandas, scipy, scikit-learn, etc.) rely on NumPy as one of their main building blocks. Plus we will use it to generate data for our analysis examples later on!
NumPy is also incredibly fast, as it has bindings to C libraries. For more info on why you would want to use arrays instead of lists, check out this great StackOverflow post.
We will only learn the basics of NumPy. To get started we need to install it!
Installation Instructions
NumPy is already included in your environment! You are good to go if you are using the course environment!
For those not using the provided environment:
It is highly recommended you install Python using the Anaconda distribution to make sure all underlying dependencies (such as Linear Algebra libraries) all sync up with the use of a conda install. If you have Anaconda, install NumPy by going to your terminal or command prompt and typing:
pip install numpy
Using NumPy
Once you’ve installed NumPy you can import it as a library:
NumPy has many built-in functions and capabilities. We won’t cover them all but instead we will focus on some of the most important aspects of NumPy: vectors, arrays, matrices and number generation. Let’s start by discussing arrays.
NumPy Arrays
NumPy arrays are the main way we will use NumPy throughout the course. NumPy arrays essentially come in two flavors: vectors and matrices. Vectors are strictly 1-dimensional (1D) arrays and matrices are 2D (but you should note a matrix can still have only one row or one column).
Let’s begin our introduction by exploring how to create NumPy arrays.
Creating NumPy Arrays
From a Python List
We can create an array by directly converting a list or list of lists:
= [1,2,3]
my_list my_list
[1, 2, 3]
np.array(my_list)
array([1, 2, 3])
= [[1,2,3],[4,5,6],[7,8,9]]
my_matrix my_matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
np.array(my_matrix)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Built-in Methods
There are lots of built-in ways to generate arrays.
arange
Return evenly spaced values within a given interval. [reference]
0,10) np.arange(
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
0,11,2) np.arange(
array([ 0, 2, 4, 6, 8, 10])
zeros and ones
Generate arrays of zeros or ones. [reference]
3) np.zeros(
array([0., 0., 0.])
5,5)) np.zeros((
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
3) np.ones(
array([1., 1., 1.])
3,3)) np.ones((
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
linspace
Return evenly spaced numbers over a specified interval. [reference]
0,10,3) np.linspace(
array([ 0., 5., 10.])
0,5,20) np.linspace(
array([0. , 0.26315789, 0.52631579, 0.78947368, 1.05263158,
1.31578947, 1.57894737, 1.84210526, 2.10526316, 2.36842105,
2.63157895, 2.89473684, 3.15789474, 3.42105263, 3.68421053,
3.94736842, 4.21052632, 4.47368421, 4.73684211, 5. ])
Note that .linspace()
includes the stop value. To obtain an array of common fractions, increase the number of items:
0,5,21) np.linspace(
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 ,
2.75, 3. , 3.25, 3.5 , 3.75, 4. , 4.25, 4.5 , 4.75, 5. ])
eye
Creates an identity matrix [reference]
4) np.eye(
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
Random
Numpy also has lots of ways to create random number arrays:
rand
Creates an array of the given shape and populates it with random samples from a uniform distribution over [0, 1)
. [reference]
2) np.random.rand(
array([0.37065108, 0.89813878])
5,5) np.random.rand(
array([[0.03932992, 0.80719137, 0.50145497, 0.68816102, 0.1216304 ],
[0.44966851, 0.92572848, 0.70802042, 0.10461719, 0.53768331],
[0.12201904, 0.5940684 , 0.89979774, 0.3424078 , 0.77421593],
[0.53191409, 0.0112285 , 0.3989947 , 0.8946967 , 0.2497392 ],
[0.5814085 , 0.37563686, 0.15266028, 0.42948309, 0.26434141]])
randn
Returns a sample (or samples) from the “standard normal” distribution [σ = 1]. Unlike rand which is uniform, values closer to zero are more likely to appear. [reference]
2) np.random.randn(
array([-0.36633217, -1.40298731])
5,5) np.random.randn(
array([[-0.45241033, 1.07491082, 1.95698188, 0.40660223, -1.50445807],
[ 0.31434506, -2.16912609, -0.51237235, 0.78663583, -0.61824678],
[-0.17569928, -2.39139828, 0.30905559, 0.1616695 , 0.33783857],
[-0.2206597 , -0.05768918, 0.74882883, -1.01241629, -1.81729966],
[-0.74891671, 0.88934796, 1.32275912, -0.71605188, 0.0450718 ]])
randint
Returns random integers from low
(inclusive) to high
(exclusive). [reference]
1,100) np.random.randint(
61
1,100,10) np.random.randint(
array([39, 50, 72, 18, 27, 59, 15, 97, 11, 14])
seed
Can be used to set the random state, so that the same “random” results can be reproduced. [reference]
42)
np.random.seed(4) np.random.rand(
array([0.37454012, 0.95071431, 0.73199394, 0.59865848])
42)
np.random.seed(4) np.random.rand(
array([0.37454012, 0.95071431, 0.73199394, 0.59865848])
Array Attributes and Methods
Let’s discuss some useful attributes and methods for an array:
= np.arange(25)
arr = np.random.randint(0,50,10) ranarr
arr
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24])
ranarr
array([38, 18, 22, 10, 10, 23, 35, 39, 23, 2])
Reshape
Returns an array containing the same data with a new shape. [reference]
5,5) arr.reshape(
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
max, min, argmax, argmin
These are useful methods for finding max or min values. Or to find their index locations using argmin or argmax
ranarr
array([38, 18, 22, 10, 10, 23, 35, 39, 23, 2])
max() ranarr.
39
ranarr.argmax()
7
min() ranarr.
2
ranarr.argmin()
9
Shape
Shape is an attribute that arrays have (not a method): [reference]
# Vector
arr.shape
(25,)
# Notice the two sets of brackets
1,25) arr.reshape(
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24]])
1,25).shape arr.reshape(
(1, 25)
25,1) arr.reshape(
array([[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12],
[13],
[14],
[15],
[16],
[17],
[18],
[19],
[20],
[21],
[22],
[23],
[24]])
25,1).shape arr.reshape(
(25, 1)
dtype
You can also grab the data type of the object in the array: [reference]
arr.dtype
dtype('int32')
= np.array([1.2, 3.4, 5.6])
arr2 arr2.dtype
dtype('float64')