Numpy
Numpy
Python
Estimated time needed: 15 minutes
Objectives
After completing this lab you will be able to:
Table of Contents
What is Numpy?
Type
Assign Value
Slicing
Assign Value with List
Other Attributes
Numpy Array Operations
Array Addition
Array Multiplication
Product of Two Numpy Arrays
Dot Product
Adding Constant to a Numpy Array
Mathematical Functions
Linspace
What is Numpy?
NumPy is a Python library used for working with arrays, linear algebra, fourier transform, and
matrices. NumPy stands for Numerical Python and it is an open source project. The array
object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very
important.
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 :
import numpy as np
a = np.array([0, 1, 2, 3, 4])
a
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
In [4]: print(np.__version__)
1.21.6
Type
If we check the type of the array we get numpy.ndarray:
type(a)
Out[5]: 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, it's a 64-bit integer:
a.dtype
Out[6]: dtype('int64')
Try it yourself
Check the type of the array and Value type for the given array c
Assign value
We can change the value of the array. Consider the array c :
c = np.array([20, 1, 2, 3, 4])
c
c[0] = 100
c
c[4] = 0
c
Try it yourself
Assign the value 20 for the second element in the given array.
Slicing
Like lists, we can slice the numpy array. Slicing in python means taking the elements from
the given index to another given index.
We pass slice like this: [start:end].The element at end index is not being included in the
output.
We can select the elements from 1 to 3 and assign it to a new numpy array d as follows:
d = c[1:4]
d
In [13]: # Set the fourth element and fifth element to 300 and 400
print(arr[1:5:2])
[2 4]
In [15]: print(arr[:4])
[1 2 3 4]
In [16]: print(arr[4:])
[5 6 7]
In [17]: print(arr[1:5:])
[2 3 4 5]
Try it yourself
Print the even elements in the given array.
[2 4 6 8]
select = [0, 2, 3, 4]
select
Out[19]: [0, 2, 3, 4]
We can use the list as an argument in the brackets. The output is the elements
corresponding to the particular indexes:
d = c[select]
d
We can assign the specified elements to a new value. For example, we can assign the values
to 100 000 as follows:
c[select] = 100000
c
a = np.array([0, 1, 2, 3, 4])
a
a.size
Out[23]: 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:
a.ndim
Out[24]: 1
The attribute shape is a tuple of integers indicating the size of the array in each dimension:
a.shape
Out[25]: (5,)
Try it yourself
Find the size ,dimension and shape for the given array b
Size= 7
Dimensions= 1
Shape (7,)
mean = a.mean()
mean
Out[86]: 0.0
standard_deviation=a.std()
standard_deviation
Out[87]: 1.0
b = np.array([-1, 2, 3, 4, 5])
b
max_b = b.max()
max_b
Out[89]: 5
min_b = b.min()
min_b
Out[32]: -1
Try it yourself
Find the sum of maximum and minimum value in the given numpy array
min_c = c.min()
print("Minnimum",min_c)
Maximum 502
Minnimum -10
Max+Min 492
Array Addition
Consider the numpy array u :
z = np.add(u, v)
z
import time
import sys
import numpy as np
Plotvec1(u, z, v)
Try it yourself
Perform addition operation on the given numpy array arr1 and arr2:
In [91]: arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
arr3 = np.add(arr1, arr2)
arr3
# Enter your code here
Array Subtraction
Consider the numpy array a:
In [94]: max_c
min_c
Out[94]: -10
In [42]: c = np.subtract(a, b)
print(c)
[ 5 10 15]
Try it yourself
Perform subtraction operation on the given numpy array arr1 and arr2:
Array Multiplication
Consider the vector numpy array y :
x = np.array([1, 2])
x
y = np.array([2, 1])
y
z = np.multiply(x, y)
z
Try it yourself
Perform multiply operation on the given numpy array arr1 and arr2:
Array Division
Consider the vector numpy array a:
In [48]: a = np.array([10, 20, 30])
a
In [50]: c = np.divide(a, b)
c
Try it yourself
Perform division operation on the given numpy array arr1 and arr2:
Dot Product
The dot product of the two numpy arrays u and v is given by:
np.dot(X, Y)
Out[53]: 7
In [54]: #Elements of X
print(X[0])
print(X[1])
1
2
In [55]: #Elements of Y
print(Y[0])
print(Y[1])
3
2
Try it yourself
Perform dot operation on the given numpy array ar1 and ar2:
Out[98]: 26
u = np.array([1, 2, 3, -1])
u
u + 1
Try it yourself
Add Constant 5 to the given numpy array ar:
Mathematical Functions
We can access the value of pi in numpy as follows :
In [60]: # The value of pi
np.pi
Out[60]: 3.141592653589793
We can apply the function sin to the array x and assign the values to the array y ; this
applies the sine function to each element in the array:
y = np.sin(x)
y
Linspace
A useful function for plotting mathematical functions is linspace . Linspace returns evenly
spaced numbers over a specified interval.
np.linspace(-2, 2, num=5)
If we change the parameter num to 9, we get 9 evenly spaced numbers over the interval
from -2 to 2:
np.linspace(-2, 2, num=9)
Out[64]: array([-2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5, 2. ])
We can use the function linspace to generate 100 evenly spaced samples from the
interval 0 to 2π:
In [65]: # Make a numpy array within [0, 2π] and 100 elements
We can apply the sine function to each element in the array x and assign it to the array y :
y = np.sin(x)
plt.plot(x, y)
Try it yourself
Make a numpy array within [5, 4] and 6 elements
[1 2 3]
But if you want to result in the form of the list, then you can use for loop:
1
2
3
u = np.array([1, 0])
v = np.array([0, 1])
u - v
z = np.array([2, 4])
-2 * z
Out[102]: array([-4, -8])
Consider the list [1, 2, 3, 4, 5] and [1, 0, 1, 0, 1] . Cast both lists to a numpy
array then multiply them together:
import time
import sys
import numpy as np
def Plotvec2(a,b):
ax = plt.axes()# to generate the full window axes
ax.arrow(0, 0, *a, head_width=0.05, color ='r', head_length=0.1)#Add an arrow t
plt.text(*(a + 0.1), 'a')
ax.arrow(0, 0, *b, head_width=0.05, color ='b', head_length=0.1)#Add an arrow t
plt.text(*(b + 0.1), 'b')
plt.ylim(-2, 2)#set the ylim to bottom(-2), top(2)
plt.xlim(-2, 2)#set the xlim to left(-2), right(2)
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 their dot product:
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 their dot product:
In [107… # Write your code below and press Shift+Enter to execute
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 their dot product:
Why are the results of the dot product for [-1, 1] and [1, 1] and the dot product for
[1, 0] and [0, 1] zero, but not zero for the dot product for [1, 1] and [0, 1] ?
Hint: Study the corresponding figures, pay attention to the direction the arrows are pointing to.
The vectors used for question 4 and 5 are perpendicular. As a result, the dot product is zero.
Click here for the solution
Convert the list [1, 2, 3] and [8, 9, 10] to numpy arrays arr1 and arr2 . Then
perform Addition , Subtraction , Multiplication , Division and Dot
Operation on the arr1 and arr2 .
[ 9 11 13]
[-7 -7 -7]
[ 8 18 30]
[0.125 0.22222222 0.3 ]
56
Convert the list [1, 2, 3, 4, 5] and [6, 7, 8, 9, 10] to numpy arrays arr1 and
arr2 . Then find the even and odd numbers from arr1 and arr2 .
Author
Dev Agnihotri