++++Notebook converted from Jupyter for blog publishing.
00-NumPy-Arrays
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 (opens in a new tab).
We will only learn the basics of NumPy. To get started we need to install it!
Note: Numpy Installation Instructions
NumPy is already included in your environment! We HIGHLY recommend using our environment as shown in the setup and installation lecture. 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:
conda install numpy
If you do not have Anaconda and can not install it, please refer to Numpy's official documentation on various installation instructions. (opens in a new tab)
Importing NumPy
Once you've installed NumPy you can import it as a library:
import numpy as npNumPy 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).
Why use Numpy array? Why not just a list?
There are lot's of reasons to use a Numpy array instead of a "standard" python list object. Our main reasons are:
- Memory Efficiency of Numpy Array vs list
- Easily expands to N-dimensional objects
- Speed of calculations of numpy array
- Broadcasting operations and functions with numpy
- All the data science and machine learning libraries we use are built with Numpy
Simple Example of what numpy array can do
my_list = [1,2,3]
my_array = np.array([1,2,3])type(my_list)listLet's begin our introduction by exploring how to create NumPy arrays.
Creating NumPy Arrays from Objects
From a Python List
We can create an array by directly converting a list or list of lists:
my_list = [1,2,3]
my_list[1, 2, 3]np.array(my_list)array([1, 2, 3])my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
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 to create arrays
There are lots of built-in ways to generate arrays.
arange
Return evenly spaced values within a given interval. [reference (opens in a new tab)]
np.arange(0,10)array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])np.arange(0,11,2)array([ 0, 2, 4, 6, 8, 10])zeros and ones
Generate arrays of zeros or ones. [reference (opens in a new tab)]
np.zeros(3)array([0., 0., 0.])np.zeros((5,5))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.]])np.ones(3)array([1., 1., 1.])np.ones((3,3))array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])linspace
Return evenly spaced numbers over a specified interval. [reference (opens in a new tab)]
np.linspace(0,10,3)array([ 0., 5., 10.])np.linspace(0,5,20)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. ]).linspace(){:python} includes the stop value. To obtain an array of common fractions, increase the number of items:
np.linspace(0,5,21)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 (opens in a new tab)]
np.eye(4)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){:python}. [reference (opens in a new tab)]
np.random.rand(2)array([0.37065108, 0.89813878])np.random.rand(5,5)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 (opens in a new tab)]
np.random.randn(2)array([-0.36633217, -1.40298731])np.random.randn(5,5)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{:python} (inclusive) to high{:python} (exclusive). [reference (opens in a new tab)]
np.random.randint(1,100)61np.random.randint(1,100,10)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 (opens in a new tab)]
np.random.seed(42)
np.random.rand(4)array([0.37454012, 0.95071431, 0.73199394, 0.59865848])np.random.seed(42)
np.random.rand(4)array([0.37454012, 0.95071431, 0.73199394, 0.59865848])Array Attributes and Methods
Let's discuss some useful attributes and methods for an array:
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)arrarray([ 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])ranarrarray([38, 18, 22, 10, 10, 23, 35, 39, 23, 2])Reshape
Returns an array containing the same data with a new shape. [reference (opens in a new tab)]
arr.reshape(5,5)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
ranarrarray([38, 18, 22, 10, 10, 23, 35, 39, 23, 2])ranarr.max()39ranarr.argmax()7ranarr.min()2ranarr.argmin()9Shape
Shape is an attribute that arrays have (not a method): [reference (opens in a new tab)]
# Vector
arr.shape(25,)# Notice the two sets of brackets
arr.reshape(1,25)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]])arr.reshape(1,25).shape(1, 25)arr.reshape(25,1)array([[ 0],
[ 1],
[ 2],
[ 3],
[ 4],arr.reshape(25,1).shape(25, 1)dtype
You can also grab the data type of the object in the array: [reference (opens in a new tab)]
arr.dtypedtype('int32')arr2 = np.array([1.2, 3.4, 5.6])
arr2.dtypedtype('float64')