0% found this document useful (0 votes)
9 views

CAP776 Numpy

Uploaded by

dipanshu020312
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

CAP776 Numpy

Uploaded by

dipanshu020312
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 88

CAP776

PROGRAMMING IN PYTHON

Created By:
Kumar Vishal
(SCA), LPU
Introduction to NumPy
 arrays vs lists,
 array creation routines,
 arrays from existing data,
 indexing and slicing,
 Operations on NumPy arrays,
 array manipulation,
 broadcasting,
 binary operators,
 NumPy functions: mathematical functions, statistical
functions, sort, search and counting functions
arrays vs lists
• An array is also a data structure that stores a collection
of items. Like lists, arrays are ordered, mutable,
enclosed in square brackets, and able to store non-
unique items.
• A list in Python is a collection of items which can
contain elements of multiple data types.
• A array in Python is a collection of items which can
contain elements of same data types
• The Python array module requires all array elements
to be of the same type.
• On the other hand, NumPy arrays support different
data types.
• NumPy stands for Numerical Python
• NumPy is a Python library used for working with arrays.
• In Python we have lists that serve the purpose of arrays,
but they are slow to process.
• NumPy aims to provide an array object that is up to 50x
faster than traditional Python lists.
• The array object in NumPy is called ndarray, it provides a
lot of supporting functions
Python, you'll need to import this data structure
from the NumPy package or the array module.
Installation of NumPy
!pip install numpy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy
Command to install numpy on windows
C:\ py –m pip install numpy
Create an alias with the as keyword while importing:
import numpy as np
Checking NumPy Version
The version string is stored under __version__ attribute
import numpy as np
print(np.__version__)
What are Modules in Python?
In python a module means a saved python file. This file can
contain a group of classes, methods, functions and variables.
What is import keyword in python?
If we want to use other members(variable, function, etc) of a
module in your program, then you should import that module by
using the import keyword. After importing you can access
members by using the name of that module.
from keyword in python:
We can import some specific members of the module
by using the from keyword. The main advantage of the
from keyword is we can access members directly
without using module names.
N-Dimensional array(ndarray) in Numpy
 NumPy is used to work with arrays.
 The array object in NumPy is called ndarray.
 We can create a NumPy ndarray object by using the array()
function.
 To create an ndarray, we can pass a list, tuple or any array-
like object into the array() method, and it will be converted
into an ndarray
Create a 1-D array containing the values
0,1,2,3,4,5:
 In numpy dimensions are called rank or axes.
 Size of the array along each dimension is known as shape of
the array
 An array can have any number of dimensions.
 When the array is created, you can define the
number of dimensions by using the ndmin argument.
There are various ways to create arrays in
NumPy:
• You can create an array from a regular Python
list or tuple using the array function.
• Functions to create arrays:
Using arange() function to create a Numpy
array.
Using arange() function to create a Numpy array:

arange(start, end, step)


Example:
arange_array = np.arange(0,11,2)
print(arange_array)
Reverse Array
arr2 = np.arange(20,0,-1)
print("Reverse Array", arr2)
Reshaping arrays
 Reshaping means changing the shape of an array.
 The shape of an array is the number of elements in each
dimension.
 By reshaping we can add or remove dimensions or change
number of elements in each dimension.
array creation routines
The ndarray object can be constructed by using
the following routines:
Numpy.empty
The empty routine is used to create an
uninitialized array of specified shape and data
type.
The syntax is given below.
numpy.empty(shape, dtype = data_type)
import numpy as np
arr = np.empty([3,2], dtype = int)
print(arr)
NumPy.Zeros
This routine is used to create the numpy array
with the specified shape where each numpy
array item is initialized to 0.
import numpy as np
arr = np.zeros((3,2), dtype = int)
print(arr)
NumPy.ones
This routine is used to create the numpy array
with the specified shape where each numpy
array item is initialized to 1.
import numpy as np
arr = np.ones((3,2), dtype = int)
print(arr)
Array From Existing Data

numpy.asarray()
Difference array() and asarray() function:
The main difference is that when you try to make a
numpy array using np.array, it would create a copy of
the object array and not reflect changes to the original
array. On the other hand, when you use numpy
asarray, it would reflect changes to the original array.
NumPy Bitwise Operators

• bitwise_and
• bitwise_or
• invert
• left_shift
• right_shift
bitwise_and

import numpy as np
a = 10
b = 12
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
print("Bitwise and of a and b: ",np.bitwise_and(a,b))
If both side bit is on result will be On

a b a&b

0 0 0

0 1 0

1 0 0

1 1 1
Steps to solve:-
• a = 12 (find binary form:1100 )
• b = 25 (find binary form:11001)
How to find Binary:
64 32 16 8 4 2 1

0 1 1 0 0 12

1 1 0 0 1
25

1 0 0 0 8
bitwise_or Operator

import numpy as np

a = 50
b = 90
print("binary representation of a:",bin(a))
print("binary representation of b:",bin(b))
print("Bitwise-or of a and b: ",np.bitwise_or(a,b))
If any side bit is on result will be On

a b a|b

0 0 0

0 1 1

1 0 1

1 1 1
Steps to solve:-
• a = 12 (find binary form:1100 )
• b = 25 (find binary form:11001)
How to find Binary:
64 32 16 8 4 2 1

0 1 1 0 0 12

1 1 0 0 1
25

1 1 1 0 1 29
Invert operation

• It is used to calculate the bitwise not


operation
left_shift()
import numpy as np

a = 10
print ('Left shift of 10 by two positions:')
print (np.left_shift(10,2))
a=10 (1010)
a<<1
1010.0
10100(20) Ans.
a<<2
1010.00
101000(40) Ans.
right_shift
import numpy as np

print 'Right shift 40 by two positions:'


print np.right_shift(40,2)
a=10 (1010)
a>>1
1010.
101(5) Ans.
a>>2
1010.
10(2) Ans.
String functions
numpy.char.add()
import numpy as np
print ('Concatenate two strings:’ )
print (np.char.add(['hello'],[' xyz’]))
numpy.char.multiply()

import numpy as np
print( np.char.multiply('Hello ‘,3))
numpy.char.center()

This function returns an array of the required


width so that the input string is centered and
padded on the left and right with fillchar.
import numpy as np
# np.char.center(arr, width,fillchar)
print (np.char.center('hello', 20,fillchar = '*’))
numpy.char.capitalize()

This function returns the copy of the string with


the first letter capitalized.

import numpy as np
print( np.char.capitalize('hello world’))
Operations on NumPy arrays
 You can perform arithmetic directly on NumPy
arrays, such as addition and subtraction.
 For example, two arrays can be added
together to create a new array where the
values at each index are added together.
import numpy as np A. [1,2,3,1,1,1]
a = np.array([1, 2, 3]) B. [1,1,1,1,2,3]
b = np.array([1, 1, 1]) C. [2,3,4]
c=a+b D. None
print(c)
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 1, 1])
c=a+b
print(c)
a = [1, 2, 3]
b = [1, 1, 1]
c=a+b
c = [1 + 1, 2 + 1, 3 + 1]
Limitation with Array Arithmetic
 Arithmetic may only be performed on arrays
that have the same dimensions and
dimensions with the same size.
 Arrays with different sizes cannot be added,
subtracted, or generally be used in arithmetic.
 A way to overcome this use array
broadcasting and is available in NumPy
arithmetic operations
For performing arithmetic operations such as add(), subtract(), multiply(), and
divide() must be of the same shape.
import numpy as np
a = np.array([10,20,30])
b = np.array([1,2,3])
print(a.shape)
print(b.shape)
print(np.add(a,b))
print(np.subtract(a,b))
print(np.multiply(a,b))
print(np.divide(a,b))
Example:
import numpy as np
a1=np.array([10,20,30])
b1=np.array([1,2,3,4])
print(a1+b1)
You can perform arithmetic operations with
different dimension using broadcasting rule :
Main rule:
• Size of each dimension should be same
• Size of one of the dimension should be 1.
array broadcasting rule
Rule1: If the two arrays differ in their number of
dimensions, the shape of the one with fewer
dimensions is padded with ones on its leading (left)
side.
Rule2: If the shape of the two arrays does not match in
any dimension, the array with shape equal to 1 in that
dimension is stretched to match the other shape.
Rule3: If in any dimension the sizes disagree and
neither is equal to 1, an error is raised.
Check with
example: a1=[10,20,30]
shape:3
dimension:1D
import numpy as np
b1=[1,2,3,4]
a1=np.array([10,20,30]) shape:4
b1=np.array([1,2,3,4]) dimension:1D
Rule1: not satisfied
print(a1+b1) Rule2:not satisfied
Check with another example2

import numpy as np
a1=np.array([[1,2],[3,4],[5,6]])
b1=np.array([10,20])
print(a1+b1)
a1:
Shape: 3,2
Dimension:2D
b1:
Shape:2
Dimension:1D
Check with another example3

import numpy as np
a1=np.array([[1,2],[3,4],[5,6]])
b1=np.array([10,20,30])
print(a1+b1)
a1:
Shape: 3,2
Dimension:2D
b1:
Shape:3
Dimension:1D
Check with another example4

import numpy as np
a1=np.array([[1,2],[3,4],[5,6]])
b1=np.array([[10,20],[30,40]])
print(a1+b1)
a1:
Shape: 3,2
Dimension:2D
b1:
Shape:2,2
Dimension:2D
mathematical functions
1. Arithmetic Functions
2. Trigonometric Functions
3. Logarithmic and Exponential Functions
4. Rounding Functions
1. Arithmetic Functions
NumPy Add function
add()
This function is used to add two arrays. If we add
arrays having dissimilar shapes we get “Value Error”.
NumPy Subtract function
subtract()
We use this function to output the difference of two
arrays. If we subtract two arrays having dissimilar
shapes we get “Value Error”.
1. Arithmetic Functions
NumPy Multiply function
multiply()
We use this function to output the multiplication of
two arrays. We cannot work with dissimilar arrays.
NumPy Divide Function
divide()
We use this function to output the division of two
arrays. We cannot divide dissimilar arrays.
1. Arithmetic Functions
NumPy Mod and Remainder function:
mod()
remainder()
We use both the functions to output the
remainder of the division of two arrays.
2. Trigonometric Functions
 np.sin()- It performs trigonometric sine calculation
element-wise.
 np.cos()- It performs trigonometric cosine calculation
element-wise.
 np.tan()- It performs trigonometric tangent calculation
element-wise.
 np.arcsin()- It performs trigonometric inverse sine
element-wise.
 np.arccos()- It performs trigonometric inverse of cosine
element-wise.
 np.arctan()- It performs trigonometric inverse of tangent
element-wise.
Real life applications of trigonometry
Trigonometry can be used to measure the
height of a building or mountains.
if you know the distance from where you observe the
building and the angle of elevation you can easily find
the height of the building.
Problem statement
A man standing at a certain distance from a building,
observe the angle of elevation of its top to be 60∘. He
walks 30 yds away from the building. Now, the angle of
elevation of the building’s top is 30∘. How high is the
building?
tan 60= h/d
√3 =h/d
d=h/√3
Conversion function

degrees(arr)
Covert input angles from radians to degrees
rad2deg(arr)
radians(arr)
Covert input angles from degrees to radians
deg2rad(arr)
Exponential and Logarithmic Functions

np.exp()- This function calculates the exponential of


the input array elements.
np.log()- This function calculates the natural log of the
input array elements. Natural Logarithm of a value is
the inverse of its exponential value.
Exponential and Logarithmic Functions

John Napier
John Napier is best known as the discoverer of
logarithms in 1614
In mathematics, the logarithm is the inverse
function to exponentiation.
Exponentiation is a mathematical operation,
written as bn, involving two numbers, the base b
and the exponent or power n, and pronounced
as "b (raised) to the (power of) n". When n is a
positive integer, exponentiation corresponds to
repeated multiplication of the base.
Inverse function
Logarithmic function is of the form
f(x) = logax
or,
y = logax,
where a > 0 and a!=1
x we can take (0 to ∞)
based on x value y value will be have range(- ∞ to ∞)

It is the inverse of the exponential function ay = x


Real life examples:

Suppose these values indicating salary, distance from earth to sun and
Molecules. You want to plot the graph for these values
If we will plot graph like this:

No’s will be seems like very closer, we can solve this using logarithmic
The Richter scale is a base-10 logarithmic scale, meaning that each order of
magnitude is 10 times more intensive than the last one.
Rounding Functions
np.around()- This function is used to round off a decimal number
to desired number of positions. The function takes two
parameters: the input number and the precision of decimal
places.
np.floor()- This function returns the floor value of the input
decimal value. Floor value is the largest integer number less than
the input value.
Sort, Search & Counting Functions
There are various sorting algorithms like quicksort, merge sort and
heapsort which is implemented using the numpy.sort() function.
Syntax:
numpy.sort(input, axis, kind, order)
input: It represents the input array which is to be sorted.
axis: It represents the axis along which the array is to be sorted. If
the axis is not mentioned, then the sorting is done along the last
available axis.
kind: It represents the type of sorting algorithm which is to be
used while sorting. The default is quick sort.
order: It represents the filed according to which the array is to be
sorted in the case if the array contains the fields.
# importing the module
import numpy as np

# creating two matrices


p = [[1, 2], [2, 3]]
q = [[4, 5], [6, 7]]
print("Matrix p :")
print(p)
print("Matrix q :")
print(q)

# computing product
result = np.dot(p, q)

# printing the result


print("The matrix multiplication is :")
print(result)

You might also like