0% found this document useful (0 votes)
33 views20 pages

Programing Using NumPy Library..... Syed Fasih - Insitute of Space & Technology

Here are the steps to evaluate the given expressions: a) R1 = np.random.random(10, 10) - This generates a random 10x10 matrix with values between 0 to 1 b) R2 = R1 < 0.5 - R2 will be a boolean matrix with True for elements in R1 less than 0.5 and False otherwise. - The logic is it compares each element of R1 with 0.5 and returns True/False. c) R1[R2] - R1[R2] selects the elements of R1 where the corresponding element in R2 is True. - The logic is it picks the elements of R1 whose

Uploaded by

Fasih Abbas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views20 pages

Programing Using NumPy Library..... Syed Fasih - Insitute of Space & Technology

Here are the steps to evaluate the given expressions: a) R1 = np.random.random(10, 10) - This generates a random 10x10 matrix with values between 0 to 1 b) R2 = R1 < 0.5 - R2 will be a boolean matrix with True for elements in R1 less than 0.5 and False otherwise. - The logic is it compares each element of R1 with 0.5 and returns True/False. c) R1[R2] - R1[R2] selects the elements of R1 where the corresponding element in R2 is True. - The logic is it picks the elements of R1 whose

Uploaded by

Fasih Abbas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

OBJECTIVES

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

Python Matrices and NumPy


A matrix is a two-dimensional data structure where numbers are arranged into rows and
columns. For example:

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.

NumPy provides multidimensional array of numbers (which is


actually an object).

Example:
importnumpy as np

a = np.array([1, 2, 3])
print(a) # Output: [1, 2, 3]
print(type(a)) # Output: <class
'numpy.ndarray'>

As you can see, NumPy's array class is called 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 = np.add(array A, arrayB)


NumPyadd()is a mathematical function and is used to calculate the addition between two
NumPy arrays. This function adds given arrays element-wise.

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.max(A) //works for 1D,


2D
np.max(A)function is the tool of choice for finding maximum values across arrays.

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

Syntax : numpy.ceil(x[, out]) = ufunc ‘ceil’)


Parameters :
a : [array_like] Input array
Return : The ceil of each element with float data-type.
ans = np.floor(array)

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.

Syntax : numpy.floor(x[, out]) = ufunc ‘floor’)


Parameters :
a : [array_like] Input array
Return : The floor of each element.

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.

Syntax : numpy.round_(arr, decimals = 0, out = None)


Parameters :
array : [array_like] Input array.
decimal : [int, optional] Decimal places we want to round off.
Default = 0. In case of -ve decimal, it specifies the n0. of positions to the
left of the decimal point.
A round command is use to round off by observing the nearest value to the number

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.

Syntax: numpy.ones(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(byDefault)] Data type of returned array.

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.

c) Print the elements in the second row.


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
 Firstly print the matrix by using print(A)
 [1,:] for printing in second row use the index 1 & should put colon(:) after

d) Print the elements in the third 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
 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:

a) R1 = np.random.random(10, 10) (you may use (2,2) initially)


b) R2 = R1 < 0.5 (Print value of R2 and Justify the logic behind it)
c) R1[R2] (Print R1[R2] and Justify the logic behind it)
d) R1[R2] = -1 (Print R1 and Justify the logic behind it)
Program:

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.

a. Add matrices element wise, using np.add(..) It also works with +


b. Add 6 to all the elements of the matrix A.
c. Double all the elements of the matrix B.
d. Try np.sum() and understand its functionality in comparison with the function
np.add().
Program:

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)

print(f’array A:\n{A}\n array B:\n{B}\n.Element wise add of A and B:\n{add}’)

A=np.add(A,6)

print(f’b.adding 6 to each element of A:\n{A_new}’)

B=np.add(B,B)

print(f’c.double every element in B:\n{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)

Print(‘Random array of 20x20:’A)

for i in range(len(A[1,:])):

A[i,i]=0

Print(‘upload array with diagnol zeros:’A)


Task # 7 Given an array A of integers, return the difference between the largest and
smallest integers in the array.

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

print(“Tax collected at day:”+str(i)+”is”,A[i])


Coclusion:
“Numpy is one of the best libraries that is available in Python for a wide range of tasks.”

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

You might also like