You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

25 KiB

<html> <head> </head>

___

Copyright Pierian Data For more information, visit us at www.pieriandata.com

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!

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.


Importing NumPy

Once you've installed NumPy you can import it as a library:

In [2]:
import numpy as np

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).

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

In [3]:
my_list = [1,2,3]
my_array = np.array([1,2,3])
In [4]:
type(my_list)
Out[4]:
list
In [ ]:

Let'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:

In [2]:
my_list = [1,2,3]
my_list
Out[2]:
[1, 2, 3]
In [3]:
np.array(my_list)
Out[3]:
array([1, 2, 3])
In [4]:
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
my_matrix
Out[4]:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [5]:
np.array(my_matrix)
Out[5]:
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]

In [6]:
np.arange(0,10)
Out[6]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [7]:
np.arange(0,11,2)
Out[7]:
array([ 0,  2,  4,  6,  8, 10])

zeros and ones

Generate arrays of zeros or ones. [reference]

In [8]:
np.zeros(3)
Out[8]:
array([0., 0., 0.])
In [9]:
np.zeros((5,5))
Out[9]:
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.]])
In [10]:
np.ones(3)
Out[10]:
array([1., 1., 1.])
In [11]:
np.ones((3,3))
Out[11]:
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

linspace

Return evenly spaced numbers over a specified interval. [reference]

In [12]:
np.linspace(0,10,3)
Out[12]:
array([ 0.,  5., 10.])
In [13]:
np.linspace(0,5,20)
Out[13]:
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:

In [14]:
np.linspace(0,5,21)
Out[14]:
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]

In [15]:
np.eye(4)
Out[15]:
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]

In [16]:
np.random.rand(2)
Out[16]:
array([0.37065108, 0.89813878])
In [17]:
np.random.rand(5,5)
Out[17]:
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]

In [18]:
np.random.randn(2)
Out[18]:
array([-0.36633217, -1.40298731])
In [19]:
np.random.randn(5,5)
Out[19]:
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]

In [20]:
np.random.randint(1,100)
Out[20]:
61
In [21]:
np.random.randint(1,100,10)
Out[21]:
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]

In [22]:
np.random.seed(42)
np.random.rand(4)
Out[22]:
array([0.37454012, 0.95071431, 0.73199394, 0.59865848])
In [23]:
np.random.seed(42)
np.random.rand(4)
Out[23]:
array([0.37454012, 0.95071431, 0.73199394, 0.59865848])

Array Attributes and Methods

Let's discuss some useful attributes and methods for an array:

In [24]:
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
In [25]:
arr
Out[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])
In [26]:
ranarr
Out[26]:
array([38, 18, 22, 10, 10, 23, 35, 39, 23,  2])

Reshape

Returns an array containing the same data with a new shape. [reference]

In [27]:
arr.reshape(5,5)
Out[27]:
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

In [28]:
ranarr
Out[28]:
array([38, 18, 22, 10, 10, 23, 35, 39, 23,  2])
In [29]:
ranarr.max()
Out[29]:
39
In [30]:
ranarr.argmax()
Out[30]:
7
In [31]:
ranarr.min()
Out[31]:
2
In [32]:
ranarr.argmin()
Out[32]:
9

Shape

Shape is an attribute that arrays have (not a method): [reference]

In [33]:
# Vector
arr.shape
Out[33]:
(25,)
In [34]:
# Notice the two sets of brackets
arr.reshape(1,25)
Out[34]:
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]])
In [35]:
arr.reshape(1,25).shape
Out[35]:
(1, 25)
In [36]:
arr.reshape(25,1)
Out[36]:
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]])
In [37]:
arr.reshape(25,1).shape
Out[37]:
(25, 1)

dtype

You can also grab the data type of the object in the array: [reference]

In [38]:
arr.dtype
Out[38]:
dtype('int32')
In [39]:
arr2 = np.array([1.2, 3.4, 5.6])
arr2.dtype
Out[39]:
dtype('float64')

Great Job!

</html>