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

CAP776 Numpy

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

CAP776 Numpy

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

CAP776

PROGRAMMING IN PYTHON

NumPy
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
NumPy
• NumPy stands for Numerical Python
• NumPy is the core library for scientific and numerical
computing in Python.
• It provides various computing tools such as comprehensive
mathematical functions, linear algebra routines.
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: np.zeros, np.ones, np.empty,
etc.
Installation of NumPy
!pip install numpy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import 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__)
Array creation using array functions :
array(value list)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
Use a tuple to create a NumPy array:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
Create a 1-D array containing the values
1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
Access Array Elements
Array indexing is the same as accessing an array
element.
You can access an array element by referring to
its index number.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[1])
# printing original array
import numpy as np
arr = np.array([1, 2, 3, 4,5])
print ("The new created array is : ",end="")
for i in range (0,5):
print (arr[i], end=" ")
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)
arrays vs lists
• A list in Python is a collection of items which
can contain elements of multiple data types. It
is an ordered collection supporting negative
indexing. A list can be created using []
containing data values.
• An array is a vector containing homogeneous
elements i.e. belonging to the same data type.
Elements are allocated with contiguous memory
locations allowing easy modification, that is,
addition, deletion, accessing of elements.
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)
Numpy array from existing data
creating numpy array using the list
import numpy as np
l=[1,2,3,4,5,6,7]
a = np.asarray(l);
print(type(a))
print(a)
numpy.asarray()
This function is similar to numpy.array except
for the fact that it has fewer parameters.
This routine is useful for converting Python
sequence into ndarray.
numpy.asarray(a, dtype = None, order = None)
creating a numpy array using Tuple
import numpy as np
l=(1,2,3,4,5,6,7)
a = np.asarray(l);
print(type(a))
print(a)
creating a numpy array using more than one
list
import numpy as np
L1=[[1,2,3,4,5,6,7],[8,9]]
a = np.asarray(l);
print(type(a))
print(a)
Create a 2-D array containing two arrays with
the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
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)
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))
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))
Invert operation

• It is used to calculate the bitwise not the


operation
left_shift()
import numpy as np

a = 10
print ('Left shift of 10 by two positions:')
print (np.left_shift(10,2))
right_shift
import numpy as np

print 'Right shift 40 by two positions:'


print np.right_shift(40,2)
String functions
numpy.char.add()
import numpy as np
print 'Concatenate two strings:'
print np.char.add(['hello'],[' xyz'])
print '\n'
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 = 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
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
• Trigonometric Functions
• Logarithms Functions
Trigonometric Functions
Trigonometric Functions

numpy.sin() NumPy function help to find sine


value of the angle in degree and radian.
numpy.cos() NumPy function help to find cosine
value of the angle in degree and radian.
numpy.tan() NumPy function help to find
tangent value of the angle in degree and radian.
Example:
Example
Example with graph
Example with graph
Logarithms Functions

Base 2: log2()
Base 10: log10()
Square root function
Square function
Rounding Functions

The numpy.round_() is a mathematical function


that rounds an array to the given number of
decimals.
Syntax : numpy.round_(arr, decimals = 0)
What will be output?

import numpy as np
a=np.array([11.23,24.05,24.90,25.16,26.53,26.62])
print(np.round(a,1))
numpy.floor()
The numpy.floor() is a mathematical function
that returns the floor of the elements of array.
numpy.ceil() function
This function is used to return the ceiling value
of the array values which is the smallest integer
value greater than the array element.
What is the difference between summation and
addition?
mport numpy as np

arr1 = np.array([1, 2, 3])


arr2 = np.array([1, 2, 3])

newarr = np.add(arr1, arr2)

print(newarr)
import numpy as np

arr1 = np.array([1, 2, 3])


arr2 = np.array([1, 2, 3])

newarr = np.sum([arr1, arr2])

print(newarr)
Products
To find the product of the elements in an array,
use the prod() function.
Example
Find the product of the elements of this array:
import numpy as np
arr = np.array([1, 2, 3, 4])
x = np.prod(arr)
print(x)
Differences

import numpy as np

arr = np.array([10, 15, 25, 5])

newarr = np.diff(arr)

print(newarr)
We can use NumPy's unique() method to find
unique elements from any array.
import numpy as np

arr = np.array([1, 1, 1, 2, 3, 4, 5, 5, 6, 7])

x = np.unique(arr)

print(x)
Finding Union
To find the unique values of two arrays, use the
union1d() method.
import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([3, 4, 5, 6])
newarr = np.union1d(arr1, arr2)
print(newarr)
Finding the minimum and maximum elements
from the array
The numpy.amin() and numpy.amax() functions
are used to find the minimum and maximum of
the array elements along the specified axis
respectively.
numpy.where() function
•This function is used to return the indices of all
the elements which satisfies a particular
condition.

You might also like