Numpy in Python


In [2]:
import time 
import sys
import numpy as np 

import matplotlib.pyplot as plt
%matplotlib inline

In [3]:
def Plotvec1(u,z,v):
    #this function is used in code 
    ax = plt.axes()
    ax.arrow(0, 0, *u, head_width=0.05,color ='r', head_length=0.1)
    plt.text(*(u+0.1), 'u')
    
    ax.arrow(0, 0, *v, head_width=0.05,color ='b', head_length=0.1)
    plt.text(*(v+0.1), 'v')
    ax.arrow(0, 0, *z, head_width=0.05, head_length=0.1)
    plt.text(*(z+0.1), 'z')
    plt.ylim(-2,2)
    plt.xlim(-2,2)



def Plotvec2(a,b):
    #this function is used in code 
    ax = plt.axes()
    ax.arrow(0, 0, *a, head_width=0.05,color ='r', head_length=0.1)
    plt.text(*(a+0.1), 'a')
    ax.arrow(0, 0, *b, head_width=0.05,color ='b', head_length=0.1)
    plt.text(*(b+0.1), 'b')

    plt.ylim(-2,2)
    plt.xlim(-2,2)

If you recall, a Python list is a container that allows you to store and access data. We can create a Python List as follows:


In [4]:
a=["0",1,"two","3",4]

We can access the data via an index:

We can access each element using a square bracket as follows:


In [5]:
print("a[0]:",a[0])
print("a[1]:",a[1])
print("a[2]:",a[2])
print("a[3]:",a[3])
print("a[4]:",a[4])


a[0]: 0
a[1]: 1
a[2]: two
a[3]: 3
a[4]: 4

A numpy array is similar to a list, it's usually fixed in size and each element is of the same type. We can cast a list to a numpy array by first importing numpy:


In [6]:
import numpy as np

We then cast the list as follows:


In [7]:
a=np.array([0,1,2,3, 4])
a


Out[7]:
array([0, 1, 2, 3, 4])

Each element is of the same type, in this case integers:

As with lists, we can access each element via a square bracket:


In [8]:
print("a[0]:",a[0])
print("a[1]:",a[1])
print("a[2]:",a[2])
print("a[3]:",a[3])
print("a[4]:",a[4])


a[0]: 0
a[1]: 1
a[2]: 2
a[3]: 3
a[4]: 4

The value of “a” is stored a follows:


In [9]:
a


Out[9]:
array([0, 1, 2, 3, 4])

If we check the type of the array we get "numpy.ndarray":


In [10]:
type(a)


Out[10]:
numpy.ndarray

As numpy arrays contain data of the same type, we can use the attribute "dtype" to obtain the Data-type of the array’s elements. In this case a 64-bit integer:


In [11]:
a.dtype


Out[11]:
dtype('int64')

We can create a numpy array with real numbers:


In [12]:
b=np.array([3.1,11.02,6.2, 213.2,5.2])

When we check the type of the array we get "numpy.ndarray":


In [13]:
type(b)


Out[13]:
numpy.ndarray

If we examine the attribute "dtype" we see float 64, as the elements are not integers:


In [14]:
b.dtype


Out[14]:
dtype('float64')

We can change the value of the array, consider the array "c":


In [15]:
c=np.array([20,1,2,3,4])
c


Out[15]:
array([20,  1,  2,  3,  4])

We can change the first element of the array to 100 as follows:


In [16]:
c[0]=100
c


Out[16]:
array([100,   1,   2,   3,   4])

We can change the 5th element of the array as follows:


In [17]:
c[4]=0
c


Out[17]:
array([100,   1,   2,   3,   0])

Like lists, we can slice the numpy array, and we can select the elements from 1 to 3 and assign it to a new numpy array 'd' as follows:


In [18]:
d=c[1:4]
d


Out[18]:
array([1, 2, 3])

We can assign the corresponding indexes to new values as follows:


In [19]:
c[3:5]=300,400
c


Out[19]:
array([100,   1,   2, 300, 400])

Similarly, we can use a list to select a specific index. The list ' select ' contains several values:


In [20]:
select=[0,2,3]

We can use the list as an argument in the brackets. The output is the elements corresponding to the particular index:


In [21]:
d=c[select]
d


Out[21]:
array([100,   2, 300])

We can assign the specified elements to a new value. For example, we can assign the values to 100 000 as follows:


In [22]:
c[select]=100000
c


Out[22]:
array([100000,      1, 100000, 100000,    400])

Let's review some basic array attributes using the array ‘a’:


In [23]:
a=np.array([0,1,2,3, 4])
a


Out[23]:
array([0, 1, 2, 3, 4])

The attribute size is the Number of elements in the array:


In [24]:
a.size


Out[24]:
5

The next two attributes will make more sense when we get to higher dimensions but let's review them. The attribute “ndim” represents the Number of array dimensions or the rank of the array, in this case, one:


In [25]:
a.ndim


Out[25]:
1

The attribute “shape” is a tuple of integers indicating the size of the array in each dimension:


In [26]:
a.shape


Out[26]:
(5,)

In [27]:
a=np.array([1,-1,1,-1])

In [28]:
mean=a.mean()
mean


Out[28]:
0.0

In [29]:
standard_deviation=a.std()
standard_deviation


Out[29]:
1.0

In [30]:
b=np.array([1,2,3,4,5])
b


Out[30]:
array([1, 2, 3, 4, 5])

In [31]:
max_b=b.max()

In [32]:
max_b=b.min()

Array Addition

Consider the numpy array 'u':


In [33]:
u=np.array([1,0])
u


Out[33]:
array([1, 0])

Consider the numpy array 'v':


In [34]:
v=np.array([0,1])
v


Out[34]:
array([0, 1])

We can add the two arrays and assign it to z:


In [35]:
z=u+v
z


Out[35]:
array([1, 1])

The operation is equivalent to vector addition:


In [36]:
Plotvec1(u,z,v)


Implement the following vector subtraction in numpy: u-v


In [37]:
u - v


Out[37]:
array([ 1, -1])

Consider the vector numpy array 'y':


In [38]:
y=np.array([1,2])
y


Out[38]:
array([1, 2])

We can multiply every element in the array by 2:


In [39]:
z=2*y
z


Out[39]:
array([2, 4])

This is equivalent to multiplying a vector by a scaler:

Multiply the numpy array z with -2:


In [40]:
-2 * z


Out[40]:
array([-4, -8])

Product of two numpy arrays

Consider the following array 'u':


In [41]:
u=np.array([1,2])
u


Out[41]:
array([1, 2])

Consider the following array 'v':


In [42]:
v=np.array([3,2])
v


Out[42]:
array([3, 2])

The product of the two numpy arrays 'u' and 'v' is given by:


In [43]:
z=u*v
z


Out[43]:
array([3, 4])

Consider the list [1,2,3,4,5] and [1,0,1,0,1], and cast both lists to a numpy array then multiply them together:


In [44]:
np.array([1,2,3,4,5]) * np.array([1,0,1,0,1])


Out[44]:
array([1, 0, 3, 0, 5])
``` a=np.array([1,2,3,4,5]) b=np.array([1,0,1,0,1]) a*b ```

Dot Product

The dot product of the two numpy arrays 'u' and 'v' is given by:


In [45]:
np.dot(u,v)


Out[45]:
7

Convert the list [-1,1] and [1,1] to numpy arrays 'a' and 'b'. Then, plot the arrays as vectors using the fuction Plotvec2 and find the dot product:


In [47]:
a = np.array([-1, 1])
b = np.array([1, 1])
Plotvec2(a, b)
np.dot(a, b)


Out[47]:
0
``` a=np.array([-1,1]) b=np.array([1,1]) Plotvec2(a,b) print("the dot product is",np.dot(a,b) ) ```

Convert the list [1,0] and [0,1] to numpy arrays 'a' and 'b'. Then, plot the arrays as vectors using the function Plotvec2 and find the dot product:


In [48]:
a = np.array([1, 0])
b = np.array([0, 1])
Plotvec2(a, b)
np.dot(a, b)


Out[48]:
0
``` a=np.array([1,0]) b=np.array([0,1]) Plotvec2(a,b) print("the dot product is",np.dot(a,b) ) ```

Convert the list [1,1] and [0,1] to numpy arrays 'a' and 'b'. Then plot the arrays as vectors using the fuction Plotvec2 and find the dot product:


In [49]:
a = np.array([1, 1])
b = np.array([0, 1])
Plotvec2(a, b)
np.dot(a, b)


Out[49]:
1
``` a=np.array([1,1]) b=np.array([0,1]) Plotvec2(a,b) print("the dot product is",np.dot(a,b) ) print("the dot product is",np.dot(a,b) ) ```

Why is the result of the dot product for question 4 and 5 zero, but not zero for question 6? Hint: study the corresponding figures, pay attention to the direction the arrows are pointing to.

perpendicular vectors vs. non-perpendicular vectors

``` The vectors used for question 4 and 5 are perpendicular. As a result, the dot product is zero. ```

Adding Constant to a numpy Array

Consider the following array:


In [51]:
u=np.array([1,2,3,-1]) 
u


Out[51]:
array([ 1,  2,  3, -1])

Adding the constant 1 to the array adds 1 to each element in the array:


In [52]:
u+1


Out[52]:
array([2, 3, 4, 0])

The process is summarised in the following animation:

This part of Broadcasting check out the link for more detail.

Mathematical Functions

We can access the value of pie in numpy as follows :


In [53]:
np.pi


Out[53]:
3.141592653589793

We can create the following numpy array in Radians:


In [54]:
x=np.array([0,np.pi/2 , np.pi] )

We can apply the function "sine" to the array 'x' and assign the values to the array 'y'; this applies the sine function to each element in the array:


In [55]:
y=np.sin(x)
y


Out[55]:
array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])

Linspace

A useful function for plotting mathematical functions is "linespace". Linespace returns evenly spaced numbers over a specified interval. We specify the starting point of the sequence and the ending point of the sequence. The parameter "num" indicates the Number of samples to generate, in this case 5:


In [56]:
np.linspace(-2,2,num=5)


Out[56]:
array([-2., -1.,  0.,  1.,  2.])

If we change the parameter num to 9, we get 9 evenly spaced numbers over the interval from -2 to 2:


In [57]:
np.linspace(-2,2,num=9)


Out[57]:
array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])

We can use the function line space to generate 100 evenly spaced samples from the interval 0 to 2 pi:


In [59]:
x=np.linspace(0,2*np.pi,num=100)
x


Out[59]:
array([0.        , 0.06346652, 0.12693304, 0.19039955, 0.25386607,
       0.31733259, 0.38079911, 0.44426563, 0.50773215, 0.57119866,
       0.63466518, 0.6981317 , 0.76159822, 0.82506474, 0.88853126,
       0.95199777, 1.01546429, 1.07893081, 1.14239733, 1.20586385,
       1.26933037, 1.33279688, 1.3962634 , 1.45972992, 1.52319644,
       1.58666296, 1.65012947, 1.71359599, 1.77706251, 1.84052903,
       1.90399555, 1.96746207, 2.03092858, 2.0943951 , 2.15786162,
       2.22132814, 2.28479466, 2.34826118, 2.41172769, 2.47519421,
       2.53866073, 2.60212725, 2.66559377, 2.72906028, 2.7925268 ,
       2.85599332, 2.91945984, 2.98292636, 3.04639288, 3.10985939,
       3.17332591, 3.23679243, 3.30025895, 3.36372547, 3.42719199,
       3.4906585 , 3.55412502, 3.61759154, 3.68105806, 3.74452458,
       3.8079911 , 3.87145761, 3.93492413, 3.99839065, 4.06185717,
       4.12532369, 4.1887902 , 4.25225672, 4.31572324, 4.37918976,
       4.44265628, 4.5061228 , 4.56958931, 4.63305583, 4.69652235,
       4.75998887, 4.82345539, 4.88692191, 4.95038842, 5.01385494,
       5.07732146, 5.14078798, 5.2042545 , 5.26772102, 5.33118753,
       5.39465405, 5.45812057, 5.52158709, 5.58505361, 5.64852012,
       5.71198664, 5.77545316, 5.83891968, 5.9023862 , 5.96585272,
       6.02931923, 6.09278575, 6.15625227, 6.21971879, 6.28318531])

We can apply the sine function to each element in the array 'x' and assign it to the array 'y':


In [60]:
y=np.sin(x)

In [61]:
plt.plot(x,y)


Out[61]:
[<matplotlib.lines.Line2D at 0x7fcf8ce904a8>]

Enjoying Python? Think ahead about what you might want to use in the future.

If you're looking for an enterprise-ready environment to use Python on a big scale with two free Apache Spark executors, consider signing up for a free account on Data Science Experience

About the Authors:

Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.

Copyright © 2017 cognitiveclass.ai. This notebook and its source code are released under the terms of the MIT License.


In [ ]: