You are on page 1of 78

Artificial Intelligence

(AI)
AGENDA

▰ Python Libraries
▰ Import & install Numpy
▰ Creating Arrays
▰ Numpy-Data types
▰ Array Attributes
▰ Indexing and slicing
▰ Array creation routines
▰ Operations on arrays
▰ Sorting arrays
▰ Method of arrays 2
Python Libraries

3
Back to main
Python library

Python library :

➢ Collection of script modules that are


accessible to a Python program.
➢ Simplify the programming process.
➢ Remove the need to rewrite commonly used
commands again and again.
➢ Some of python useful libraries are Numpy,
Pandas, Plotly, Keras, Tensorflow etc
Image Ref:
https://www.fiverr.com/anirudhnegi/setup-amazon

4
Import & Install Numpy

5
Back to main
NumPy in python

➢ Stands for ‘Numerical Python’.


➢ an open-source library for the Python programming language.
➢ provides a multidimensional array object.
➢ Derived objects (matrices)
➢ an assortment of routines for fast operations on arrays
➢ Provides high-level functioning tools for working with arrays.
➢ used for scientific computing and working with arrays.

6
NumPy in python

Basic linear
algebra
Logical &
Shape
mathematical
manipulation
operations

NumPy also
Sorting & Discrete Fourier
selecting provides transforms

Random
I/O
simulation

Basic statistical
operations 7
Key features of NumPy Python

N-
dimensional
Python array
object
for
sophisticated
integrating C,
broadcasting
C++, and
function
Fortran code

NumPy
key features

random
linear algebra number
capabilities

Fourier
Transform
8
Installing NumPy

5 Steps :- Check Python Version

Install pip

Install Numpy

Verify Numpy Installation

Import Numpy Package


9
Step 1: Check Python Version

Most likely, you have Python 2 or Python 3 installed, or


even both versions.
Check Python 3 Version:

Python3-V or python3

The output give you a


version number.
❖ For python 3: 3.11

10
Step 2: Install Pip

PIP for Python:


➢ Stands for “preferred installer program” or “Pip Installs
Packages

➢ Package management system for installing Python


software.

utility to manage PyPI package installations from the


command line.

11
Step 3: Install NumPy

✓ With Pip set up, can use its command line for
installing NumPy.

Install NumPy with Python 3 :

pip install numpy

12
Step 4: Verify NumPy Installation

✓ show command to verify whether NumPy is part of you


Python packages:

Show NumPy with Python:

Pip show numpy

13
Step 5: Import the NumPy Package

✓ After installing NumPy import the package ,


using :

Command to Import NumPy :

import numpy as np

14
Back to main
Creating Arrays:

Array :
❖ NumPy is used to work with arrays.
❖ Array object in NumPy called ndarray.
create a NumPy ndarray object by using the array() function.

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
output: [1, 2, 3, 4, 5]
15
Back to main
Creating Arrays:

Example:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
type():
print(type(arr)) ➢ built-in Python
output: [1 2 3 4 5] function define type
<class 'numpy.ndarray'>
of the object passed
to it.
➢ code shows that arr is
numpy.ndarray type. 16
Creating Arrays:

Use a tuple to create a NumPy


array:
.
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
output:
[1,2,3,4,5]

17
Creating Arrays:

Dimensions in Arrays:
A dimension in arrays is one level of array depth.
Nested array: arrays that have arrays as their elements.
Following are some dimensions in array:
1. 0-D Arrays
2. 1-D Arrays
3. 2-D Arrays
4. 3-D Arrays
5. N-D Arrays 18
Creating Arrays:

0-D Arrays:
❑ Scalars, are the elements in
an array.
❑ Each value in an array is a
0-D array. Example:
import numpy as np
arr = np.array(42)
print(arr)
output: 42
19
Creating Arrays:

1-D Arrays:
❑ Array that has 0-D arrays as
its elements is called uni-
dimensional or 1-D array.
Example:
❑ Most common and basic
arrays. import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
output: [1,2,3,4,5]
20
Creating Arrays:

2-D Arrays:
Example:
❑ Array that has 1-D arrays as its elements is
import numpy as np
called a 2-D array.
arr = np.array([[1, 2, 3], [4, 5, 6]])

❑ Often used to represent matrix or 2nd order print(arr)


tensors. output:
[[1 2 3]
NumPy has a whole sub module dedicated [4 5 6]]
towards matrix operations called numpy.mat

21
Creating Arrays:

3-D Arrays:
❑ Array that has 2-D arrays Example:
(matrices) as its import numpy as np
elements is called 3-D arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
array.
❑ Often used to represent output:
[[[1 2 3]
a 3rd order tensor. [4 5 6]]
[[1 2 3]
[4 5 6]]]

22
Creating Arrays:

N-D Arrays:
❑ Arrays provides the number of dimensions (ndim) attribute
that returns an integer that tells us how many dimensions
the array have.

23
Creating Arrays:

import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5]) output:

c = np.array([[1, 2, 3], [4, 5, 6]]) 0

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

print(a.ndim) 2

print(b.ndim) 3

print(c.ndim)
print(d.ndim)

24
Back to main
NumPy Data Types

❑ A data type object tells how the bytes in the fixed-size block of memory corresponding
to an array item should be interpreted.
❑ It describes the following aspects of the data
i. Type of the data (String, integer, float, Python object, etc.)
ii. Size of the data ( total bytes is in e.g. the float)
iii. Byte order of the data (small-endian or big-endian)
iv. If the data type is structured data type, an aggregate of other data types, (e.g.,
describing an array item consisting of string and Boolean)
v. If the data type is a sub-array, then show its shape and data type.

25
Back to main
NumPy Data Types

By default, Python have these data types:


Data Type Description
strings Represent text data, the text is given under
quotation marks. e.g. "ABCD"

integer Represent integer numbers. e.g. -1, -9, -3

float Represent real numbers. e.g. 1.5, 46.42

Boolean Represent (True or False).

complex Represent complex numbers. e.g. 1.0 + 4.0j,


1.57+ 2.5
26
NumPy Data Types

Data Type Description


bool_ Boolean (True or False) as a byte
int_ Integer type (either int64 or int32)

intc Identical (normally int32 or int64)

intp Integer used for indexing (either int32 or int64)


int8 Byte (-128 to 127)

int16 Integer (-32768 to 32767)


int32 Integer (-2147483648 to 2147483647)

int64 Integer (-9223372036854775808 to 9223372036854775807)

uint8 Unsigned integer (0 to 255) 27


Back to main

Data Type Description


uint16 Unsigned integer (0 to 65535)

uint32 Unsigned integer (0 to 4294967295)

uint64 Unsigned integer (0 to 18446744073709551615)

float_ Shorthand for float64

float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa

float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa

float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa

complex_ Shorthand for complex128 28


Attributes of a NumPy Array

Array Attributes:
❑ NumPy array (ndarray class) used in Machine Learning and
Deep Learning.
❑ create a Numpy array first, say, array_A.
❑ Pass the above list to array() function of NumPy

array_A = np.array([ [2,4,8], [0,8,1] ])

29
Back to main
Attributes of a NumPy Array

Array Attributes:
some important attributes
of ndarray object are:

ndarray.ndim ndarray.shape ndarray.size ndarray.dtype ndarray.itemsize

30
Attributes of a NumPy Array

ndarray.ndim:
❑ ndim represents number of dimensions (axes) of the ndarray.
❑ For this 2-dimensional array [ [3,4,6], [0,8,1]]
❑ for this 2-dimensional array [ [3,4,6], [0,8,1]], value of ndim will
be 2.
# an array of evenly spaced
numbers
import numpy as np
a = np.arange(24)
print a
Output:
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23] 31
Attributes of a NumPy Array

ndarray.shape:
❑ array attribute returns a tuple consisting of array
dimensions.
❑ also used to resize the array.
❑ Shape is a tuple of integers representing the size of import numpy as np
the ndarray in each dimension. A = np.array([[1,2,3],[4,5,6]])
print a.shape
❑ For this 2-dimensional array [ [3,4,6], [0,8,1]]
❑ Shape value will be (2,3) because ndarray has two Output:
dimensions rows and columns & number of rows is 2 (2, 3)
and number of columns is 3 .

32
Attributes of a NumPy Array

ndarray.size:
❑ size is total no’s of elements in ndarray.
❑ Equal to product of elements of shape.
❑ For this 2-dimensional array [ [3,4,6], [0,8,1]], product
(multiplication) of 2 and 3 (2*3) = 6.
❑ size is 6.

33
Attributes of a NumPy Array

ndarray.dtype:
❑ Data type of the elements of a NumPy array.
❑ In NumPy array, all the elements have the same data type.
❑ For this NumPy array [ [3,4,6], [0,8,1]], dtype will be int64.

34
Attributes of a NumPy Array

ndarray.itemsize:
❑ Returns the size (in bytes) of each element of a NumPy array.
❑ For this 2-dimensional array [ [3,4,6], [0,8,1]], itemsize will be 8,
because this array consists of integers and size of integer (in
bytes) is 8 bytes.
dtype of array is int8 (1 byte)
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print x.itemsize

Output:
1
35
Back to main
Array Indexing

Access Array Elements:


❖ Indexing in array is the same as accessing an array elements.
❖ Array elements can be accessed by referring to its index number.
❖ In NumPy arrays indexes start with 0.
❖ Means first element has index 0, and second has index 1 etc.

import numpy as np import numpy as np import numpy as np

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

print(arr[0]) print(arr[1]) print(arr[2] + arr[3])


Output: Output: Output:
0 5 16

36
Back to main
Array Indexing

Access 2-D Arrays:


❖ Use comma separated integers to access elements from 2-D arrays which shows dimension
and index of the element.
❖ i-e 2-D arrays like a table with rows and columns, where the row shows dimension and index
shows column.

import numpy as np import numpy as np

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

print('2nd element on 1st row: ', arr[0, 1]) print('5th element on 2nd row: ', arr[1, 4])
Output: Output:
2nd element on 1st dim: 2 5th element on 2nd dim: 10

37
Array Indexing

Access 3-D Arrays:

❖ Use comma separated integers to access elements from 2-D arrays which shows
dimension and index of the element.

#Access the third element of the second array of the first array:

import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])
Output:
6

38
Array Indexing

Negative Indexing:

❖ Use to access an array from the end.

import numpy as np

# NumPy array with elements from 1 to 9 import numpy as np


x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
# Index values can be negative.
arr = x[np.array([1, 3, -3])] print('Last element from 2nd dim: ', arr[1, -1])
print("\n Elements are : \n",arr) Output:
10
Output:
Elements are :
39
[2 4 7]
Numpy Slicing Arrays

Slicing arrays:

➢ In python slicing means taking elements from one given index to another given index.
➢ Basic slicing is an extension of Python's basic concept of slicing to n dimensions.
➢ Pass slice instead of index like: [start:end].
➢ Also define step, like: [start:end:step].
➢ If don't pass start its take 0.
➢ If don't pass end its take length of array in that dimension.
➢ If don't pass step its take 1.

40
Numpy Slicing Arrays

# Python program for basic slicing.


import numpy as np
# Arrange elements from 0 to 19
a = np.arrange(20)
print("\n Array is:\n ",a) #Slice elements from index 1 to index 5:
# a[start:stop:step] import numpy as np
print("\n a[-8:17:1] = ",a[-8:17:1])
# The : operator means all elements till the end. arr = np.array([1, 2, 3, 4, 5, 6, 7])
print("\n a[10:] = ",a[10:])
Output: print(arr[1:5])
Array is: Output:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] [2, 3, 4, 5]
a[-8:17:1] = [12 13 14 15 16]
a[10:] = [10 11 12 13 14 15 16 17 18 19]

41
Numpy Slicing Arrays

#slice from the index 3 from the end to index


1 from the end:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
#Slice elements from the beginning to
Output: index 4 :
[5,6]
#Slice elements from index 4 to the end of the
import numpy as np array:
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[:4]) import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
Output: print(arr[4:])
[1,2,3,4]
Output:
[5, 6, 7] 42
Numpy Slicing Arrays

STEP:
✓ Step value use to find the step of the slicing.

#Return every other element from index 1 to index 5: #Return every other element from the
entire array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7]) import numpy as np
print(arr[1:5:2]) arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])
Output:
[2 4] Output:
[1 3 5 7]

43
Numpy Slicing Arrays

Slicing 2-D Arrays:

#From the second element, slice elements from index #From both elements, return index 2:
1 to index 4 (not included):
import numpy as np
import numpy as np arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) print(arr[0:2, 2])
print(arr[1, 1:4])
Output:
Output: [3 8]
[7 8 9]

44
Numpy Slicing Arrays

Slicing 2-D Arrays:

#From both elements, slice index 1 to index 4 (not import numpy as np


included), this will return a 2-D array: a = np.arange(10)
b = a[2:7:2]
import numpy as np print("\n Array is:\n ",b)
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])
Output:
Output: [2 4 6]
[[2 3 4]
[7 8 9]]
45
Numpy Slicing Arrays

#multi-dimenetional ndarray
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print("Multi-dimension Array:\n ",a) # slice single item
# slice items starting from index
print(“slice the array from index 1: \n ", a[1:]) import numpy as np
a = np.arange(10)
Output: b = a[5]
[[1 2 3] print("\n Array is:\n ",b)
[3 4 5]
[4 5 6]] Output:
Now we will slice the array from the index a[1:] 5
[[3 4 5]
[4 5 6]]

46
Numpy Slicing Arrays

Output:
Our array is:
# array to begin with [[1 2 3]
import numpy as np [3 4 5]
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) [4 5 6]]
print(“original array is\n ", a) The items in the second column are:
# this returns array of items in the second column [2 4 5]
print(“array items in 2nd coloumn\n ", a[...,1]) The items in the second row are:
# Now we will slice all items from the second row [3 4 5]
print(“array items from 2nd row: \n ", a[1,...]) The items column 1 onwards are:
# Now we will slice all items from column 1 onwards [[2 3]
print(“all items from column 1 to ownwards: \n ", a[...,1:] [4 5]
[5 6]]

47
Back to main
Array creation Routines ✓ Numpy arrays can be
created in different
ways.
✓ There are several array
creation routines in
Numpy which are used
to create ndarray
Numpy.empty() Numpy.zeros() Numpy.ones() Numpy.eye()
objects.
✓ Return a new array of
given shape and type,
without initializing
entries.

Numpy.identity Numpy.arrange Numpy.mat Numpy.full Numpy.asarray

48
Back to main
Array creation Routines

numpy.empty()
❑ Creates an uninitialized array of specified shape and datatype.
❑ Return a new array of given shape and type, without initializing
entries.
#numpy.empty(shape_of_array, dtype)
a = np.empty([2,2], dtype=int)
print(a)
Output:
[[-1933827570 -1488114077]
[ 1223320673 -1686004302]]
49
Array creation Routines

numpy.zeros():
❑ creates an array filled with zeros.
❑ Return a new array of given shape and type, filled with zeros.

#numpy.zeros(shape, dtype)
x = np.zeros([2,2], dtype=int)
print(x)
Outout:

[[0 0]
[0 0]]
50
Array creation Routines

Numpy.ones():
❑ Creates an an array filled with ones.
❑ Return a new array of given shape and type, filled with ones.

#numpy.ones(shape,dtype)
x = np.ones([2,2])
print(x)
Output:
[[1. 1.]
[1. 1.]]
51
Array creation Routines

#numpy.eye(N,M,k=0,dtype)
#where
#N → no. of rows
#M → no. of columns numpy.eye():
#k → index of the diagonal

x = np.eye(3,k=0, dtype=int) ❑ Creates 2d array with


print(x)
Output: ones on the diagonal
[[1 0 0]
[0 1 0]
and zeros elsewhere.
[0 0 1]]

x = np.eye(3)
print(x)
Output:
[[1. 0. 0.]
[0. 1. 0.] 52
[0. 0. 1.]]
Array creation Routines

Numpy.identity():
❑ Returns the identity array.
❑ 1’s on main diagonal.

#numpy.identity(n,dtype)
x = np.identity(4, dtype=int)
print(x)
Output:
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]
53
Array creation Routines

numpy.arrange()
❑ Creates an array with a specified range.

#numpy.arange(value,<start><stop><step>):
x = np.arange(10)
print(x)
y = np.arange(0,10)
print(y)
z = np.arange(0,10,2)
print(z)
Output:
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 2 4 6 8] 54
Array creation Routines

numpy.mat():
❑ Interpret the input as a matrix

x = np.array([[1,2],[3,4],[5,6]])
y = np.asmatrix(x)
print(y)
Output
[[1 2]
[3 4]
[5 6]]
print(type(x))
Output
<class ‘numpy.ndarray’>
55
#numpy.asarray(data, dtype)
#where
#a --> i/p data [lists, tuples, ndarrays] that can be converted to an array. Back to main
x = np.asarray([[1,2],[3,4]], dtype=int)
print(x)
Output:
[[1 2]
[3 4]]
x = np.asarray(np.array([(1,2,3),(4,5,6)]), dtype=int)
print(x)
Output
numpy.asarray():
[[1 2 3]
[4 5 6]] ❑ Converts a sequence type
x = np.asarray([1,2,3,4,5], dtype=int)
print(x) into a numpy array
Output
[1 2 3 4 5]
x = np.asarray([(1,2),(3,4)])
print(x)
Output
[[1 2]
[3 4]]
print(type(x))
Output
<class ‘numpy.ndarray’>
56
Numpy Arithmetic Operations

Addition

Statistical
Subtraction
functions

Arithmetic Operators

Division Multiplication
57
Back to main
Numpy Addition

Addition can be performed on numpy arrays using "+" operator

Performing addition Performing addition using numpy


using arithmetic operator function

a = np.array([5, 72, 13, 100]) a = np.array([5, 72, 13, 100])


b = np.array([2, 5, 10, 30]) b = np.array([2, 5, 10, 30])
Add_result = a+b Add_result = np.add(a, b)
print(Add_result) print(Add_result)

[ 7 77 23 130] [ 7 77 23 130]

58
Numpy Subtraction

Subtraction can be performed using "-" and built-in function i.e "subtract()"

Performing Performing
subtraction using arithmetic subtraction using numpy function
operator
a = np.array([19, 5, 1, 222])
a = np.array([19, 5, 1, 222]) b = np.array([2, 55, 11, 40])
b = np.array([2, 55, 11, 40]) result = np.subtract(a,b)
result = a - b print(result)
print(result)
[ 17 -50 -10 182] [ 17 -50 -10 182]

59
Numpy Multiplication

Muliplication can be performed using "*" and built-in function i.e "multiply()"

Performing multiplication Performing multiplication


using arithmetic operator using numpy function

a = np.array([4, 72, 12, 100]) a = np.array([4, 72, 12, 100])


b = np.array([4, 5, 6, 100]) b = np.array([4, 5, 6, 100])
result= a * b result = np.multiply(a,b)
print(result) print(result)

[ 16 360 72 10000] [ 16 360 72 10000]

60
Numpy Division

Division can be performed using "/" and built-in function i.e "divide()"

Performing division using Performing division using


arithmetic operator Numpy operator
[ 16 360 72 10000]
a = np.array([4, 75, 12, 100]) a = np.array([4, 75, 12, 100])
b = np.array([4, 5,6,100]) b = np.array([4, 5,6,100])
result= a / b result= np.divide(a,b)
print(result) print(result)

[ 1. 15. 2. 1.] [ 1. 15. 2. 1.]

61
Statistical Functions

Performing mod on two matrices Performing remainder on two


a = np.array([5, 72, 13, 100]) matrices
b = np.array([2, 5, 10, 30]) a = np.array([4, 75, 12, 100])
result= np.mod(a, b) b = np.array([4, 5,6,100])
print(result) result= np.remainder (a,b)
print(result)
[ 1 2 3 10 ]
[0 0 00]

Performing mean of all no. In


matric 'a'
a = np.array([4, 75, 15, 100])
result= np.mean(a)
print(result)
48.5 62
Assignment

▰ Calculate average of all numbers in an array


▰ Calculate sum of all numbers in an array
▰ Calculate variance of all numbers in an array
▰ Calculate power where one array as base and returns it raised to the power of the
corresponding element in the second array.
▰ Calculate maximum in an array
▰ Calculate median in an array
▰ Calculate minimum in an array
▰ Calculate the percentile in an array.
▰ Calculate the standard deviation
▰ Calculate the harmonic mean of an array.

63
Numpy Comparison Operators

Greater

Not_equal Greater_equal

Array_equal Less

Less_equal 64
"Greater than" function

Using Numpy functions


arr1 = np.array([0, 5, 2, 1])
arr2=np.array([1, 0, 7, 2])
print('Greater Than or Equal to 2 : ', np.greater(arr1, 2))
print('Result of arr1 > arr2 ', np.greater(arr1 , arr2))
Greater Than or Equal to 2: [False True True False]
Result of arr1 > arr2: [False True False False]

Using arithmetic functions


print('Greater Than or Equal to 2 : ', arr1> 2)
print('Result of arr1 > arr2 ', arr1 > arr2)
Greater Than or Equal to 2: [False True True False]
Result of arr1 > arr2: [False True False False]
"Greater than or equal to" -function

Using Function
arr1 = np.array([0, 5, 2, 1])
arr2=np.array([1, 0, 7, 2])
print('Greater Than or Equal to 2:', np.greater_equal(arr1, 2))
Click to add text
print('arr1 is greater or equal to arr2:', np.greater_equal(arr1, arr2))
Greater Than or Equal to 2: [False True True False]
arr1 is greater or equal to arr2: [False True False False]

Using arithmetic symbols


print('Greater Than or Equal to 2:', arr1 >= 2)
print('arr1 is greater or equal to arr2:', arr1 >= arr2)
Greater Than or Equal to 2: [False True True False]
arr1 is greater or equal to arr2: [False True False False]
66
Less than or equal to

Less than or equal to


arr1 = np.array([0, 5, 2, 1])
arr2 = np.array([1, 0, 7, 2])
print(Less Than or Equal to 2 : ', np.less_equal(arr1, 2))
print(Less Than or Equal to 2 : ', np.less(arr1, 2))
print('Result of arr1 < arr2 :', arr1 < arr2)
print('Result of arr1 <= arr2 :', arr1 <= arr2)

Less Than or Equal to 2 : [ True False True True]


Result of arr1 < arr2 [ True False True True]
Result of arr1 <= arr2 [ True False True True]

67
"Equal"- function

x = np.array([4, 9, 7, 0, 8, 6, 0, 10])
print('x Equal to 0 = ', x == 0)
x Equal to 0 = [False False False True False
False True False]

x = np.array([4, 9, 7, 0])
Y = np.array([4, 6, 0, 10])
print('x Equal to y = ', x == y)
print ('x equals to y', np.equal(x,y))
x Equal to y = [ True False False False]
x equals to y [ True False False False]

68
" not equal" - function

x = np.array([4, 9, 7, 0, 8, 6, 0, 10])
print('x Equal to 0 = ', x != 0)
x not Equal to 0 = [True True True False True
True True True ]

x = np.array([4, 9, 7, 0])
Y = np.array([4, 6, 0, 10])
print ('x equals to y', np.not_equal(x,y))
x Equal to y = [ True False False False]
x equals to y [ True False False False]

69
Copying Numpy Arrays

Copy View

Copy is a new array View is just a view of original array

Elements in copied arrays do not Elements in view are dependent on


depend on original array original array
Any changes made to copied array Modification in view will affect
will not affect original array elements of original array and vice
versa
Elements are physically stored in A different view of the same memory
another location. content is provided.

70
Numpy Array creation-No Copy by Assigning

An array can be assigned to another variable and declared as copied array but the id
of the array will stay same

#array declaration
arr = np.array([3, 5, 7, 9,11])
#assigning arr to newarr
newarr = arr
# both arr and newarr have same id Output
print("id of arr", id(arr)) id of arr 001209
print("id of newarr", id(nc)) id of newarr 001209
# updating newarr original array-[12 5 7 9 11]
newarr[0]= 12 assigned array-[12 5 7 9 11]
# printing the values
print("original array- ", arr)
print("assigned array- ", newarr) 71
Numpy Array creation- copy()

An array can be assigned to another variable by using "copy()" function, but id of


both arrays will be different

Creating a copy and modification in original array


#array declaration
arr = np.array([3, 5, 7, 9,11])
#copying the arr
Newarr = arr.copy()
# both arr and newarr have different id
print("id of arr", id(arr)) Output
print("id of newarr", id(nc)) id of arr 0012099
# updating newarr id of newarr 013409
newarr[4]= 13 original array-[3 5 7 9 11]
# printing the values assigned array-[3 5 7 9 13]
print("original array- ", arr)
print("assigned array- ", newarr) 72
Back to main

Numpy Array creation- view()

An array can be assigned to another variable by using "view()" function, a different


view of the same memory content is provided.

View creation and modification in original array


#array declaration
arr = np.array([3, 5, 7, 9,11])
#assigning arr to newarr
newarr = arr.view()
# both arr and newarr have same id Output
print("id of arr", id(arr)) id of arr 001209
print("id of newarr", id(nc)) id of newarr 101339
# updating changing original array will effect view original array-[3 5 7 9 13]
arr[4]= 13 assigned array-[3 5 7 9 13]
# printing the values
print("original array- ", arr)
73
print("assigned array- ", newarr)
Sorting Array

▰ Sorting refers to organizing data in ascending or


descending order
▰ Numpy arrays can be sorted in an ordered sequence
such as numerical or alphabetical order

74
Back to main
Sorting 1-D array

Sorting in ascending order Sorting in descending order


arr = arr =
np.array([10,11,2,7,9,0,12,20,15,3,6,4]) np.array([7, 1, 15, 2, 24, 9, 3, 4, 2,
arr.sort() 8, 11])
print("sorted array: ", arr) arr = np.sort(arr)[::-1]
print('In Descending Order: ', arr)
sorted array: [ 0 2 3 4 6 7 9 10 11 12 15 20]
In Descending Order: [24 15 11 9 8 7 4 3 2 2 1]

75
Sorting 2-D array

Sort along asix 0 i.e. sort contents of each Column in numpy array

Create a 2D Numpy array list of list


arr2D = np.array([[8, 7, 1, 2], [3, 2, 3, 1],
[29, 32, 11, 9]])
arr2D.sort(axis=0)
print('Sorted Array : ')
print(arr2D)
Sorted Array :
[[ 3 2 1 1]
[ 8 7 3 2]
[29 32 11 9]]

76
Sorting 2-D array

Sort along asix 0 i.e. sort contents of each row in numpy array

arr2D = np.array([[8, 7, 1, 2], [3, 2, 3,


1], [29, 32, 11, 9]])
arr2D.sort(axis=1)
print('Sorted Array : ')
print(arr2D)
Sorted Array :
[[ 1 2 7 8]
[ 1 2 3 3]
[ 9 11 29 32]]

77
Back to main
Methods of Array

▰ Numpy.reshape(): Changes the shape of a NumPy array.


▰ Numpy.transpose(): Transposes a NumPy array.
▰ Numpy.dot(): Computes the dot product of two NumPy arrays.
▰ Numpy.sum(): Computes the sum of the elements in a NumPy array.
▰ Numpy.mean(): Computes the mean of the elements in a NumPy array
▰ Numpy.min(): Computes the minimum value of the elements in a NumPy
array.
▰ Numpy.max(): Computes the maximumof the elements in a NumPy array.
▰ Numpy.concatenate(): Joins two or more NumPy arrays.

78
Back to main

You might also like