NumPy (or Numpy) is a Linear Algebra Library for Python, the reason it is so important for Data Science with Python is that almost all of the libraries in the PyData Ecosystem rely on NumPy as one of their main building blocks.
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 install the NumPy modeule and learn the basics of NumPy.
I hope you have successfully installed Python using Anaconda distribution. After installing Anaconda, to install NumPy, go to your terminal or command prompt and type:
conda install numpy
Once you've installed NumPy you can import it as a library:
import numpy as np
Numpy has many built-in functions and capabilities. 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 essentially come in two flavors: vectors and matrices. Vectors are strictly 1-d arrays and matrices are 2-d (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.
We can create an array by directly converting a list or list of lists:
my_list = [1,2,3] # create a list
my_list
np.array(my_list) # convert the list to an array
my_matrix = [[1,2,3],[4,5,6],[7,8,9]] # create a matrix
my_matrix
np.array(my_matrix) # convert the matrix in an array
There are lots of built-in ways to generate Arrays
Return evenly spaced values within a given interval.
np.arange(0,10)
np.arange(0,11,2)
Generate arrays of zeros or ones
np.zeros(3)
np.zeros((5,5))
np.ones(3)
np.ones((3,3))
Return evenly spaced numbers over a specified interval.
np.linspace(0,10,3)
np.linspace(0,10,50)
Creates an identity matrix
np.eye(4)
np.random.rand(2)
np.random.rand(5,5)
Return a sample (or samples) from the "standard normal" distribution. Unlike rand which is uniform:
np.random.randn(2)
np.random.randn(5,5)
Return random integers from low
(inclusive) to high
(exclusive).
np.random.randint(1,100)
np.random.randint(1,100,10)
Let's discuss some useful attributes and methods or an array:
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
arr
ranarr
Returns an array containing the same data with a new shape.
arr.reshape(5,5)
These are useful methods for finding max or min values. Or to find their index locations using argmin or argmax
ranarr
ranarr.max()
ranarr.argmax()
ranarr.min()
ranarr.argmin()
Shape is an attribute that arrays have (not a method):
# Vector
arr.shape
# Notice the two sets of brackets
arr.reshape(1,25)
arr.reshape(1,25).shape
arr.reshape(25,1)
arr.reshape(25,1).shape
You can also grab the data type of the object in the array:
arr.dtype
You can easily perform array with array arithmetic, or scalar with array arithmetic. Let's see some examples:
import numpy as np
arr = np.arange(0,10)
arr + arr
arr * arr
arr - arr
# Warning on division by zero, but not an error!
# Just replaced with nan
arr/arr
# Also warning, but not an error instead infinity
1/arr
arr**3
Numpy comes with many universal array functions, which are essentially just mathematical operations you can use to perform the operation across the array. Let's see some common ones:
#Taking Square Roots
np.sqrt(arr)
#Calcualting exponential (e^)
np.exp(arr)
np.max(arr) #same as arr.max()
np.sin(arr)
np.log(arr)
In this section we will discuss how to select elements or groups of elements from an array.
import numpy as np
#Creating sample array
arr = np.arange(0,11)
#Show
arr
The simplest way to pick one or some elements of an array looks very similar to python lists:
#Get a value at an index
arr[8]
#Get values in a range
arr[1:5]
#Get values in a range
arr[0:5]
Numpy arrays differ from a normal Python list because of their ability to broadcast:
#Setting a value with index range (Broadcasting)
arr[0:5]=100
#Show
arr
# Reset array, we'll see why I had to reset in a moment
arr = np.arange(0,11)
#Show
arr
#Important notes on Slices
slice_of_arr = arr[0:6]
#Show slice
slice_of_arr
#Change Slice
slice_of_arr[:]=99
#Show Slice again
slice_of_arr
Now note the changes also occur in our original array!
arr
Data is not copied, it's a view of the original array! This avoids memory problems!
#To get a copy, need to be explicit
arr_copy = arr.copy()
arr_copy
The general format is arr_2d[row][col] or arr_2d[row,col]. I recommend usually using the comma notation for clarity.
arr_2d = np.array(([5,10,15],[20,25,30],[35,40,45]))
#Show
arr_2d
#Indexing row
arr_2d[1]
# Format is arr_2d[row][col] or arr_2d[row,col]
# Getting individual element value
arr_2d[1][0]
# Getting individual element value
arr_2d[1,0]
# 2D array slicing
#Shape (2,2) from top right corner
arr_2d[:2,1:]
#Shape bottom row
arr_2d[2]
#Shape bottom row
arr_2d[2,:]
Let's briefly go over how to use brackets for selection based off of comparison operators.
arr = np.arange(1,11)
arr
arr > 4
bool_arr = arr>4
bool_arr
arr[bool_arr]
arr[arr>2]
x = 2
arr[arr>x]
You can go through the following examples for more practice
np.zeros(10)
np.ones(10)
np.ones(10) * 5
np.arange(10,51)
np.arange(10,51,2)
np.arange(9).reshape(3,3)
np.eye(3)
np.random.rand(1)
np.random.randn(25)
np.arange(1,101).reshape(10,10) / 100
np.linspace(0,1,20)
mat = np.arange(1,26).reshape(5,5)
mat
mat.sum()
mat.std()
mat.sum(axis=0)
mat.sum(axis=1)
I hope you enjoyed learning NumPy and some of its most useful functions and operations. If you want to explore NumPy even further I suggest you visit the NumPy documentation page