Programing Using NumPy Library..... Syed Fasih - Insitute of Space & Technology
Programing Using NumPy Library..... Syed Fasih - Insitute of Space & Technology
This lab will introduce NumPy and overview some of the key functionality.:
Aims to provide an array object that is up to 50x faster than traditional Python lists
To provides a lot of supporting functions that make working with ndarray very easy.
This matrix is a 3x4 (pronounced "three by four") matrix because it has 3 rows and 4 columns.
Python Matrix
Python doesn't have a built-in type for matrices. However, we can treat a list of a list as a matrix.
For example:
A = [[1, 4, 5],
[-5, 8, 9]]
We can treat this list of a list as a matrix having 2 rows and 3 columns.
NumPy
NumPy is a package for scientific computing which has support for a powerful N-dimensional
array object.
Before you can use NumPy, you need to install it however we can
use it on googlecolab without downloading as there is already
installed.
Example:
importnumpy as np
a = np.array([1, 2, 3])
print(a) # Output: [1, 2, 3]
print(type(a)) # Output: <class
'numpy.ndarray'>
We usually give the library a shorter name by using the import-as mechanism:
Once this import is done, you can use to functions from the numpy library using np as the
qualifier.
importnumpyasnp
Creator of numpy:
NumPy was created in 2005 by Travis Oliphant.
Task # 1
Explain the following functions in 1-2 lines along with examples
ans = np.sum(array)
This function is used to compute the sum of all elements, the sum of each row, and the sum of
each column of a given array.
ans = np.sqrt(array)
np.sqrt(array)function is used to return the non-negative square root of an array element-
wise (for each element of the array)
ans = np.square(array)
Python np.square(array) function returns a new array with the element value as the square
of the source array elements.It’s a utility function to quickly get the square of the matrix
elements.
ans = array.T
The transpose of a matrix is obtained by moving the rows
data to the column and columns data to the rows. If we
have an array of shape (X, Y) then the transpose of the
array will have the shape (Y, X).We can use the
transpose() function to get the transpose of an array.
ans =
np.min(A) //works for 1D, 2D
np.min(A)function is the tool of choice for finding minimum values across arrays.
ans = np.ceil(array)
np.ceil(array) function is used to return the ceil values for each element of an input
array (element-wise). This function takes two arguments arr and out and returns a new array
with ciel values for the source array arr.
Ceil command:
A ceil command is use to round up the provided data up just like ceil of room
The np.floor(array) is a mathematical function that returns the floor of the elements of
array. The floor of the scalar x is the largest integer i, such that i <= x.
A floor command is use to round up the provided data down just like floor of room
ans = np.round(array)
The np.round(array)is a mathematical function that rounds an array to the given number of
decimals.
ans =
array.reshape(r,c)
The array.reshape(r,c)function shapes an array without changing the data of the array.
Syntax:
numpy.reshape(array, shape, order = 'C')
Parameters :
array : [array_like]Input array
shape : [int or tuples of int] e.g. if we are arranging an array with 10 elements then
shaping it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2)
order : [C-contiguous, F-contiguous, A-contiguous; optional]
Return Type:
Array which is reshaped without changing the data.
ans = np.ones(n)
The np.ones() function returns a new array of given shape and type, with ones.
Returns :
ndarray of ones having given shape, order and datatype.
ans = np.zeros(m)
The np.zeros() function returns a new array of given shape and type, with zeros.
Syntax:
numpy.zeros(shape, dtype = None, order = 'C')
Parameters :
shape : integer or sequence of integers
order : C_contiguous or F_contiguous
C-contiguous order in memory(last index varies the fastest)
C order means that operating row-rise on the array will be slightly quicker
FORTRAN-contiguous order in memory (first index varies the fastest).
F order means that column-wise operations will be faster.
dtype : [optional, float(byDeafult)] Data type of returned array.
Returns :
ndarray of zeros having given shape, order and datatype.
Task # 2
Create a vector of length 20, where each component has the value 1. Then replace odd
index values with 0. (use numpy.ones())
Explanation:
Use np.ones(20)
Set the range 1-20 with increment of 2
To replace odd index value with 0 using
Task
equality mark set the selected array with the
#3
element
Create a in range i 10x10
random matrix. (use
numpy.random.rand(r,c))
Program:
Explanation:
Import the numpy library
To create 10x10 random matrix use the function np.random.rand(10,10)
Where 10,10 are representing rows and column respectively
a) Print the element in the first row, and the first column.
Program:
Explanation:
Import the numpy library
To create 10x10 random matrix use the function np.random.rand(10,10)
Where 10,10 are representing rows and column respectively
A is assigned as random array of 10x10 order
[0,0] represents first row & first column respectively.
b) Set the element in last row, and the last column to -1 and then print the
matrix.
Program:
Explanation:
Import the numpy library
To create 10x10 random matrix use the function np.random.rand(10,10)
Where 10,10 are representing rows and column respectively
A is assigned as random array of 10x10 order
[9,9] represents tenth row & tentht column respectively and to set the element equal to -1
we assigned -1 after these row column number.
Explanation:
Import the numpy library
To create 10x10 random matrix use the function np.random.rand(10,10)
Where 10,10 are representing rows and column respectively
A is assigned as random array of 10x10 order
Firstly print the matrix by using print(A)
[1,:] for printing in second row use the index 1 & should put colon(:) after
Explanation:
Import the numpy library
To create 10x10 random matrix use the function np.random.rand(10,10)
Where 10,10 are representing rows and column respectively
A is assigned as random array of 10x10 order
Firstly print the matrix by using print(A)
[:,2] for printing in third column use the index 2 & should put colon(:) before
e) Replace all the elements in the second row with 0 and then print the
matrix.
Explanation:
Import the numpy library
To create 10x10 random matrix use the function np.random.rand(10,10)
Where 10,10 are representing rows and column respectively
A is assigned as random array of 10x10 order
Set the range 10
A[1,:]=0 its mean we are dealing with second row and making it zero.
Task # 4
Evaluate the following:
import numpy as np
R1=np.random.rand(10,10)
R1=np.round(R1,decimals=2)
R2=R1<0.5
print(R1)
print(R2)
print(R1[R2])
print(‘As R1[R2] print 1-D array and values less then 0.5 or where R2
is’”True”)
R1[R2]=-1
print(R1)
print(‘R1[R2]=-1 replace those values to -1 which are less then 0.5 or where R2
is’”True”)
Task # 5
Create two matrices, A and B, of random numbers, with the 5x5 shape.
import numpy as np
A=np.random.rand([5,5])
B=np.random.rand([5,5])
A=A.round(2)
B=B.round(2)
add=np.add(A,B)
A=np.add(A,6)
B=np.add(B,B)
print(‘\n.above all statment use np.add()and its function is adding\n\,array in 1st argument,now using
np.sum():’)
sum=np.sum(A)
print(function of np.sum()is to return the all elements in array\n\ and return a number(sum),not an array.\n so
np.sum(A) is:’,sum)
Task # 6
Create a random matrix with size 20x20. Add 0 in its diagonal. Print the matrix. (use some
intelligent logic rather than adding 0 one by one, you may start with 5x5 for better view of the
output)
Program:
import numpy as np
A=np.random.rand(10,10)
A=np.round(A,decimals=2)
for i in range(len(A[1,:])):
A[i,i]=0
A = [10,15,20,2,10,6]
import numpy as np
A=np.array([])
for i in range(5):
A=np.append(int(input("Enter value: ")),A)
minimum=min(A)
maximum=max(A)
difference=maximum-minimum
print(difference)
Task # 8 Design a Toll Plaza Booth System for Motorway M2, Pakistan. (Strategies
mentioned in task)
import numpy as np
x=’N’
Tax=0
A=np.array([ ])
while(x!=’S’):
x=input(“enter vehical(N,P,S)”)
if(x==’N’):
tax=tax
elif(x==’P’):
tax=tax+10
elif(x==’D’):
A=np.append(A,tax)
tax=0
elif(x==’S’):
A=np.append(A,tax)
for i in range(len(A)):
While machines are not the best with textual or visual information, when these are
converted into mathematical arrays with the help of numpy, the computation of many critical
tasks becomes possible. Apart from improved compatibility, it also becomes easier to achieve
certain tasks. Hence, numpy is one of the best libraries that data scientists must seek to master.
Reference:
https://www.programiz.com/python-programming/matrix