4 Numpy
4 Numpy
(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 :
4
Import & Install Numpy
5
Back to main
NumPy in python
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
Install pip
Install Numpy
Python3-V or python3
10
Step 2: Install Pip
11
Step 3: Install NumPy
✓ With Pip set up, can use its command line for
installing NumPy.
12
Step 4: Verify NumPy Installation
13
Step 5: Import the NumPy Package
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:
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]])
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:
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
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
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
29
Back to main
Attributes of a NumPy Array
Array Attributes:
some important attributes
of ndarray object are:
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
36
Back to main
Array Indexing
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
❖ 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:
import numpy as np
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
41
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
#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
#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.
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)
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
[ 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()"
60
Numpy Division
Division can be performed using "/" and built-in function i.e "divide()"
61
Statistical Functions
63
Numpy Comparison Operators
Greater
Not_equal Greater_equal
Array_equal Less
Less_equal 64
"Greater than" 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]
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
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()
74
Back to main
Sorting 1-D array
75
Sorting 2-D array
Sort along asix 0 i.e. sort contents of each Column in numpy array
76
Sorting 2-D array
Sort along asix 0 i.e. sort contents of each row in numpy array
77
Back to main
Methods of Array
78
Back to main