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

Chapter 5. Numeric Computing with Numpy (1)

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

Chapter 5. Numeric Computing with Numpy (1)

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

Chapter 5

Numeric Computing with Numpy


Chapter Content
• 1. Introduction to NumPy
• 2. Numpy Data Types
• 3. Numpy Getting Started
• 4. Numpy Array
• 5. Numpy Linear Algebra
• 6. Numpy Matrix Library Matlib
• 7. Input/Output with Numpy

Python 2
1. Introduction to NumPy
• In 2005, Travis Oliphant created NumPy
• Travis Oliphant is an American data
scientist and businessman
• NumPy (Numerical Python) is an open source library in Python used to work
with array data structures and related fast numerical routines
• Array oriented computing, Efficiently implemented multi-dimensional arrays

Python 3
1. Introduction to NumPy
• NumPy is relied upon by scientists, engineers, and many other professionals around
the world

4
1. Introduction to NumPy
• Convenient interface for working with multi-dimensional array data structures
efficiently (ndarray object).
• Using fixed memory to store data (same data type) and less memory than
Lists (different data type) .
• Allocate contiguous memory
• High computational efficiency

PyObject_HEAD PyObject_HEAD
Data …
length 0x133718 …

Dimensions items 0x133748 …

strides 0x133730 …
… Lists …
0x133760

Numpy Array 0x133700 …

0x1337e8 …

Python 5
2. Numpy Data Types
• Supports a much greater variety of numerical types than Python does
Data Types Keywords/Sub Data Types
Boolean bool_

Integer int_, intc, intp, int8, int16, int32, int64

Unsigned Integer uint8, uint16, uint32, uint64

Float float_, float 16, float32, float 64

Complex complex_, complex64, complex128

Python 6
3. Numpy Getting Started
• Installing Numpy: pip install numpy
• Import Numpy: import numpy
• Alias of Numpy: import numpy as np
• Check Numpy version: np.__version__

Python 7
4. Numpy Array
• ndarray object (N-Dimensional array) 3-D Array  Tensor
19 20 21
0-D Array 2-D Array  Matrix 10 11 2212 23 24
1 2 3
1 1 2 3 13 14 2515 26 27
Axis 0 4 5 6 Axis 0 4 5 6
np.array(1) 16 17 18
7 8 9 7 8 9
Axis 2
Axis 1 Axis 1
np.array([[1, 2, 3], np.array([[[1, 2, 3],
[4, 5, 6], [4, 5, 6],
1-D Array  Vector [7, 8, 9]]) [7, 8, 9]],
[[10,11,12],
1 2 3 [13,14,15],
np.array([1, 2, 3]) [16,17,18]],
[[19,20,21],
[22,23,24],
[25,26,27]]])
Python 8
4. Numpy Array
• Numpy Array Creation
• Numpy Array Indexing
• Numpy Array Slicing
• Numpy Arithmetic Operations
• Numpy Arithmetic Functions
• Numpy Array Manipulation Functions
• Numpy Broadcasting
• Numpy Statistical Operations

Python 9
4. Numpy Array: Numpy Array Creation
• Using the array()method
import numpy as np
arr = np.array([1, 2, 3, 4, 5])

• Converting from lists, tuples  Create array from available data.


• Syntax: np.array(Data)

Data: Input data (list, tuple, or other data types).

list1 = [1, 2, 3, 4, 5] tuple1 = (1, 2, 3, 4, 5)


arr = np.array(list1) arr = np.array(tuple1)

Python 10
4. Numpy Array: Numpy Array Creation
• Using special methods:
• randint(start, end): return a random integer in range [start, end] including the end points
• numpy.random.rand(): return a array of defined shape, filled with random values.
• numpy.eye(): returns a 2-D array with 1’s as the diagonal and 0’s elsewhere
• numpy.full(shape,fill_value,dtype=None,order = ‘C’): return a
new array with the same shape and type as a given array filled with a fill_value
• numpy.random.random(): return a array of random floats in the interval [0.0, 1.0).
• arange([start,] stop[,step,][,dtype]): returns an array with evenly spaced
elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop)
• numpy.zeros(): returns a new array of given shape and type, with zeros.
• numpy.ones(): returns a new array of given shape and type, with ones.
• numpy.empty(shape, dtype = float, order = ‘C’): return a new array
of given shape and type, with random values.

Python 11
4. Numpy Array: Numpy Array Creation

import numpy as np [1065353216 1065353216]


empty_array = np.empty(2, dtype=int)
[0., 0., 0., 0., 0.]
zeros_array = np.zeros(5)
[[1., 0., 0.],
[0., 1., 0.],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arange_array = np.arange(0, 10)
[0., 0., 1.]]
eye_matrix = np.eye(3)

[[5, 6, 2], randint_array = np.random.randint(1, 10,(3, 3))


[9, 3, 3],
[9, 9, 1]] rand_array = np.random.rand(2, 3)

[[0.56549245, 0.06168123, 0.71656376],


[0.7808586, 0.53067687, 0.86072789]]
12
4. Numpy Array: Numpy Array Attributes
ndarray.shape (3,3)
return the size of array 9
(Number of elements ndarray.size
of each dimension)
return number of
ndarray.ndim
1 2 3 elements in the array
4 5 6
2
return number of array ndarray.itemsize
dimension 7 8 9
return the size (in bytes)
ndarray.dtype of elements in the array 8

return data type of


elements in the array int64

Python 13
4. Numpy Array: Numpy Array Attributes
arr : [1, 2, 3, 4, 5]
Shape of arr: (5 ,)
import numpy as np Size of arr: 5
Data type of arr: int64
arr = np.array([1 , 2, 3, 4, 5]) Number of dimensions of
print("arr :", arr) arr: 1
print("Shape of arr:", arr.shape)
print("Size of arr:", arr.size)
print("Data type of arr :", arr.dtype)
print("Number of dimensions of arr:", arr.ndim)

14
4. Numpy Array: Numpy Array Indexing
• NumPy allows to access each element of an array using its index
1-D Array:  ArrayName[i] 3-D Array:  ArrayName[i,j,k]
i
10 11 12
1 2 3 k
20 21 22 13 16 17
arr[0] 10 11 12 23 24 25 20 21 22

j 13 14 15 26 27 28
2-D Array:  ArrayName[i,j]
j 16 17 18 i
20 21 22 arr[1,1,2]
i 23 24 25
26 27 28 Note: The Index of first element is a 0
The Index of last element is a -1
arr[1,0]
15
4. Numpy Array: Numpy Array Indexing
The first element of arr1d:1
import numpy as np The last element of arr1d:5
arr1d = np.array([1 , 2, 3, 4, 5])
first_element = arr1d[0]
print("The first element of arr1d: ", first_element )
last_element = arr1d[-1]
print("The last element of arr1d: ",last_element )

[[1, 2, 3],
import numpy as np
[4, 5, 6]]

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


print(arr2d)
element_1_2 = arr2d[0, 1]
print(element_1_2 )

16
4. Numpy Array: Numpy Array Slicing
• Slicing in NumPy to extract a part of an array using its the index range

ArrayName_1D[start_Index:end_Index]
• 1-D Array

1 2 3 • 2-D Array
j
arr[:1]
• 3-D Array 10 11 12 10 11 12 13 14
k
20 21 22 13 16 17 15 16 17 18 19
23 24 25 20 21 22 i 20 21 22 23 24
10 11 12
j 13 14 15 26 27 28 25 26 27 28 29
16 17 18 i arr[1:,2:4]
arr[:2,1:,:2]
Python 17
4. Numpy Array: Numpy Array Slicing
ArrayName_2D[start_Indexi:end_Indexi, start_Indexj:end_Indexj]
j

1 2
i 3 4
5 6

1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
5 6 5 6 5 6 5 6

Arr[2:, 1:] Arr[1:, :] Arr[:1,:1] Arr[:,:]


Python 18
4. Numpy Array: Numpy Array Slicing

ArrayName_DD[start_Indexi:end_Indexi, start_Indexj:end_Indexj,
[start_Indexk:end_Indexk ]

19
4. Numpy Array: Numpy Array Slicing
30 31 32
30 31 32 k
k 20 21 22 33 34 35
20 21 22 33 34 35
10 11 12 23 24 25 36 37 38
10 11 12 23 24 25 36 37 38
arr[1:2,2:,:] j 13 14 15 26 27 28 arr[0:1,:,1:]
j 13 14 15 26 27 28
16 17 18
16 17 18 i
i
30 31 32 30 31 32
k k
20 21 22 33 34 35 20 21 22 33 34 35
10 11 12 23 24 25 36 37 38 10 11 12 23 24 25 36 37 38
j 13 14 15 26 27 28 arr[2:,:,:] j 13 14 15 26 27 28 arr[:,1:2,2:2]
16 17 18 16 17 18
i i
30 31 32 30 31 32
k k
20 21 22 33 34 35 20 21 22 33 34 35
10 11 12 23 24 25 36 37 38 10 11 12 23 24 25 36 37 38
j 13 14 15 26 27 28 arr[:,1:2,:] j 13 14 15 26 27 28 arr[:,:,0:1]
16 17 18 16 17 18
i i

Python 20
4. Numpy Array: Numpy Array Slicing
import numpy as np
arr1d = np.array ([1 , 2, 3, 4, 5]) arr1d: [1, 2, 3, 4, 5]
slice_arr1d = arr1d[1:4] Sclicing arr1d from 1 to 3:
print ("arr1d:", arr1d ) [2, 3, 4]
print ("Sclicing arr1d frome 1 to 3:",slice_arr1d)

arr2d:
import numpy as np [[1, 2, 3],
arr2d = np.array( [4, 5, 6],
[[1, 2, 3], [7, 8, 9]]
[4, 5, 6], Slicing arr2d from row 2 to
[7, 8, 9]]) row 3 and column 2 to column
end:
slice_arr2d = arr2d[1:3 , 1:] [[5, 6],
print("arr2d:\n", arr2d ) [8, 9]]
print("Slicing arr2d from row 2 to row 3 and
column 2 to column end:\n", slice_arr2d )
21
4. Numpy Array: Manipulation Functions
• transpose() method:
• Create a new array by transposing a 2-dimensional numpy array.
• Syntax: new_array = original_array.transpose()

import numpy as np
original_array = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
[[1, 4, 7],
new_array = original_array.transpose() [2, 5, 8],
print(new_array) [3, 6, 9]]

22
4. Numpy Array: Manipulation Functions
• reshape() method:
• Create a new array by changing the shape from another array
• Syntax: new_array = np.reshape(original_array, shape))

import numpy as np
original_array = np.array([[0, 1],
[2, 3],
[4, 5]])

new_array=np.reshape(original_array, (2,3)) [[0, 2, 4],


print(new_array) [1, 3, 5]]

23
4. Numpy Array: Manipulation Functions
array 2D:
• reshape() method [[1,2,3],
[4,5,6]] (2,3)
new array 2D :
import numpy as np [[1,2],
[3,4],
arr_2D = np.array([[1 , 2, 3], [4, 5, 6]]) [5,6]] (3, 2)
# (2, 3) ->(3, 2) array 1D:
new_arr_2D = np.reshape(arr_2D , (3, 2)) [1,2,3,4,5,6] (6,)
# 2D -> 1D
arr_1D = np.reshape(arr_2D , newshape =(6 , ))
print("array 2D:\n", arr_2D , arr_2D.shape )
print("new array 2D :\n", new_arr_2D, new_arr_2D.shape)
print("array 1D:\n", arr_1D, arr_1D.shape)

24
4. Numpy Array: Manipulation Functions
• resize() method:
• Change the size of an array
• Syntax: original_array.resize(row_number, column_number)

import numpy as np
original_array = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
[[1, 2, 3, 4],
original_array.resize(3,4) [5, 6, 7, 8],
print(original_array) [9, 0, 0, 0]]

25
4. Numpy Array: Manipulation Functions
• insert() method: [[10, 10, 10],
• Create a new array by inserting values from another array [ 1, 2, 3],
[ 4 , 5, 6],
• Syntax: new_array =np.insert(original_array, index, value,axis) [ 7, 8, 9]]

[[ 1, 2, 3],
import numpy as np
[ 4, 5, 6],
original_array = np.array([[1, 2, 3],
[4, 5, 6], [ 7, 8, 9],
axis =0 [7, 8, 9]]) [10, 10, 10]]
axis =1
new_array1 = np.insert(original_array,0,[10,10,10],axis=0) [[10, 1, 2, 3],
new_array2 = np.insert(original_array,3,[10,10,10],axis=0) [10, 4, 5, 6],
new_array3 = np.insert(original_array,0,[10,10,10],axis=1) [10, 7, 8, 9]]
new_array4 = np.insert(original_array,3,[10,10,10],axis=1)
[[ 1, 2, 3, 10],
[ 4, 5, 6, 10],
[ 7, 8, 9, 10]]
26
4. Numpy Array: Manipulation Functions
• append() method:
• Create a new array by appending values along the mentioned axis at the end of
the array
• Syntax: new_array =np.append(original_array, value, axis)

import numpy as np
original_array1 = np.array([[1, 2, 3],
[[ 1,2,3,10,20,30],
[4, 5, 6], [ 4,5,6,40,50,60],
axis =0 [7, 8, 9]]) [ 7,8,9,70,80,90]] [[ 1,2,3],
[ 4,5,6],
axis =1 [ 7,8,9],
original_array2 = np.array([[10, 20, 30],
[40, 50, 60],
[10,20,30],
axis =0 [70, 80, 90]]) [40,50,60],
[70,80,90]]
axis =1
new_array1 = np.append(original_array1,original_array2,axis=1)
new_array2 = np.append(original_array1,original_array2,axis=0)

27
4. Numpy Array: Manipulation Functions
• delete() method:
• Returns a new array with the deletion of sub-arrays along with the mentioned
axis
• Syntax: new_array =np.delete(original_array, index, axis) [[4, 5, 6],
[7, 8, 9]]

import numpy as np [[2, 3],


original_array = np.array([[1, 2, 3], [5, 6],
[4, 5, 6], [8, 9]]
axis =0 [7, 8, 9]])
[[1, 2, 3],
axis =1 [4, 5, 6]]
new_array1 = np.delete(original_array,0,axis=0)
new_array2 = np.delete(original_array,0,axis=1) [[1, 2],
new_array3 = np.delete(original_array,2,axis=0) [4, 5],
new_array4 = np.delete(original_array,2,axis=1) [7, 8]]

28
4. Numpy Array: Manipulation Functions
[[0, 1, 3],
[[0, 2, 4],
[5, 7, 9], axis =0
axis =0 [7, 8, 9]]
[6, 8, 10]]

axis =1 axis =1

a b
[[0, 1, 3,]
[[0, 1, 3, 0, 2, 4], [[0, 1, 3, 0, 2, 4], [0, 2, 4],
[5, 7, 9, 6, 8, 10]] [5, 7, 9, 6, 8, 10]] [5, 7, 9],
[6, 8, 10]]
np.concatenate((a,b),axis=1) np. hstack ((a , b)) np. vstack ((a , b))

29
4. Numpy Array: Manipulation Functions

import numpy as np
arr_1 = np.array([1 , 2, 3])
arr 1: [1, 2, 3]
arr_2 = np.array([4 , 5, 6])
arr 2: [4, 5, 6]
arr_3 = np.hstack((arr_1 , arr_2)) Result_arr:
print("arr 1:\n", arr_1) [1, 2, 3, 4, 5, 6]
print("arr 2:\n", arr_2)
print("Result_arr:\n", arr_3)

import numpy as np
arr_1 = np.array([1 , 2, 3]) arr 1:[1, 2, 3]
arr_2 = np.array([4 , 5, 6]) arr 2:[4, 5, 6]
arr_3 = np.vstack((arr_1 , arr_2)) Result_arr:
print("arr 1:", arr_1) [[1, 2, 3],
print("arr 2:", arr_2) [4, 5, 6]]
print("Result_arr:\n", arr_3)

30
4. Numpy Array: Manipulation Functions
Array 1:
import numpy as np [[1,2,3],
[4,5,6]]
arr_1 = np.array([[1 , 2, 3],
[4, 5, 6]]) Array 2:
arr_2 = np.array([[7 , 8, 9], [[7,8,9],
[10 , 11, 12]]) [10,11,12]]

arr_3 = np.concatenate((arr_1, arr_2),axis =0) Result(axis =0):


arr_4 = np.concatenate((arr_1, arr_2),axis =1) [[1,2,3],
[4,5,6],
print("Array 1:\n", arr_1) [7,8,9],
print("Array 2:\n", arr_2) [10,11,12]]
print("Result( axis =0) :\n",arr_3)
print("Result( axis =1) :\n",arr_4) Result(axis =1):
[[1,2,3,7,8,9],
[4,5,6,10,11,12]]

31
4. Numpy Array: Manipulation Functions
• Add a New Axis to a Numpy Array:
• There are various ways to add a new axis to a NumPy array
• Using
• newaxis() method
• expand_dims() method
• reshape() method

32
4. Numpy Array: Manipulation Functions
• newaxis() method array 1:[1,2,3] (3,)
array 2:[[1,2,3],] (1, 3)
import numpy as np array 3:
[[[[[1]
# array 1D [2]
arr_1 = np.array([1 , 2, 3]) [3]]]]] (1, 1, 1, 3, 1)

# 1D -> 2D
arr_2 = arr_1[np.newaxis, :]

# 2D -> 5D
arr_3 = arr_2[np.newaxis, :, np.newaxis ,:, np.newaxis]
print("array 1: ", arr_1 , arr_1.shape)
print("array 2: ", arr_2 , arr_2.shape)
print("array 3:\n ", arr_3 , arr_3.shape)

33
4. Numpy Array: Manipulation Functions
• expand_dims() method array 1: [1,2,3] (3,)
array 2: [[1,2,3],] (1, 3)
import numpy as np array 3:
[[[[[1]
arr_1 = np.array([1 , 2, 3]) [2]
[3]]]]] (1, 1, 1, 3, 1)
# 1D -> 2D
arr_2 = np.expand_dims(arr_1 , axis =0)

# 2D -> 5D
arr_3 = np.expand_dims(arr_2 ,axis =(0 , 2, 4))

print("array 1:", arr_1 , arr_1.shape)


print("array 2:", arr_2 , arr_2.shape)
print("array 3:\n", arr_3 , arr_3.shape)

34
4. Numpy Array: Manipulation Functions
• Sort the elements of the array in ascending order . ([[1 , 7, 3],
[10, 8, 6],
• Syntax: np.sort(arr , [axis] ) axis =0 [5, 15, 9]])
• arr: input array axis =1
• axis: sort direction Original array:
[[1,7,3],
import numpy as np [10,8,6],
arr2d = np. array ([[1 , 7, 3], [5,15,9]]
[10, 8, 6], Result by row:
[5, 15, 9]]) [[1,3,7],
print("Original array\n",arr2d) [6,8,10],
sort_in_row = np.sort(arr2d , axis =1) [5,9,15]]
sort_in_col = np.sort(arr2d , axis =0) Result by col:
print("Result by row:\n", sort_in_row) [[1,7,3],
print("Result by col:\n", sort_in_col) [5,8,6],
[10,15,9]]

35
4. Numpy Array: Numpy Broadcasting
• Broadcasting:
• Allows performing mathematical operations on arrays of different sizes
• When done operations, NumPy automatically expands smaller arrays so that they
are the same size as the larger array
•  Thereby, saving memory and optimizing performance

0 0 0 0 1 2 0 1 2
10 10 10 0 1 2 10 11 12

stretch
20 20 20 + 0 1 2 = 20 21 22
30 30 30 0 1 2 30 31 32

A (4 x 3) B (3) Result (4 x 3)

Python 36
4. Numpy Array: Numpy Broadcasting
• Broadcasting Rules:
• If the arrays don’t have the same rank then prepend the shape of the lower
rank array with 1s until both shapes have the same length.
• The two arrays are compatible in a dimension if they have the same size in
the dimension or if one of the arrays has size 1 in that dimension.
• The arrays can be broadcast together iff they are compatible with all
dimensions.
• After broadcasting, each array behaves as if it had shape equal to the
element-wise maximum of shapes of the two input arrays.
• In any dimension where one array had size 1 and the other array had size
greater than 1, the first array behaves as if it were copied along that

Python 37
4. Numpy Array: Numpy Arithmetic Operations
[[0, 3, 1],
[3, 7, 5], [10, 5, 11]
[6, 4, 8]]
b
a
np.add(a,b) np.subtract(a,b) np.multiply(a,b)
[[10,8,12], [[-10,-2,-10], [[0,15,11],
13,12,16], [-7,2,-6], [30,35,55],
[16,9,19]] [-4,-1,-3]] [60,20,88]]

[[0., 0.6, 0.09090909],


np.divide(a,b) [0.3, 1.4, 0.45454545],
[0.6, 0.8, 0.72727273]]
Python 38
4. Numpy Array: Numpy Arithmetic Operations
add_array =
[[10, 8, 12],
import numpy as np [13, 12, 16],
a = np.array ([[0, 3, 1], [16, 9, 19]]
[3, 7, 5], subtract_array =
[6, 4, 8]]) [[-10, -2, -10],
[ -7, 2, -6],
b = [10, 5, 11] [ -4, -1, -3]]
multiply_array =
print("add_array =\n",np.add(a,b)) [[ 0, 15, 11],
print("subtract_array =\n",np.subtract(a,b)) [30, 35, 55],
print("multiply_array =\n",np.multiply(a,b)) [60, 20, 88]]
print("divide_array =\n",np.divide(a,b)) divide_array =
[[0. , 0.6, 0.09090909],
[0.3, 1.4, 0.45454545],
[0.6, 0.8, 0.72727273]]

39
4. Numpy Array: Numpy Arithmetic Operations

[7,3,4,5,1] [3,4,5,6,7]

a b
np.remainder(a,b) np.power(a,b)
[1, 3, 4, 5, 1] [343, 81,1024,15625, 1]

np.mod(a,b) np.reciprocal(a)
[1, 3, 4, 5, 1] [0, 0, 0, 0, 1]

Python 40
4. Numpy Array: Numpy Arithmetic Operations
• Returm sum value in the array.
• array: input array
• Syntax: np.sum(array,[axis]) • axis: search direction
[[0, 3, 1],
axis =0 [ 3, 7, 5], [10, 5, 10]
[ 6, 4, 8]]
b
a
axis =1
np.sum(a) 37
np.sum(b) 25
np.sum(a , axis =0) [9, 14, 14]
np.sum(a , axis =1) [4, 15, 18]

41
4. Numpy Array: Numpy Arithmetic Operations

import numpy as np
a = np.array ([[0, 3, 1],
[3, 7, 5], Sum_a = 37
[6, 4, 8]]) Sum_b = 26
Sum_a_axis_0 = [ 9, 14, 14]
b = [10, 5, 11] Sum_a_axis_1 = [ 4, 15, 18]
print("Sum_a =", np.sum(a))
print("Sum_b =", np.sum(b))
print("Sum_a_axis_0 =", np.sum(a,axis=0))
print("Sum_a_axis_1 =", np.sum(a,axis = 1))

42
4. Numpy Array: Numpy Statistical Operations
• Returm the largest/smallest value in the array.
• Syntax:
np.max(array , [axis] ) • array: input array
np.min(array , [axis] ) • axis: search direction

import numpy as np
arr = np. array ([1 , 2, 3, 4, 5])
largest value : 5
max_value = np.max(arr)
print("largest value :", max_value) Smallest value: 1
min_value = np.min(arr)
print("Smallest value:", min_value)

43
4. Numpy Array: Numpy Statistical Operations
[[1, 2, 3],
axis =0 [4, 5, 6]] Maximum value in row: [3, 6]
axis =1 Maximum value in col: [4, 5, 6]
Minimum value in row: [1, 4]
Minimum value in col: [1 2, 3]
import numpy as np
arr2d = np.array ([[1 , 2, 3], [4, 5, 6]])
max_value_row = np.max(arr2d , axis =1)
max_value_col = np.max(arr2d , axis =0)
print("Maximum value in row:", max_value_row)
print("Maximum value in col:", max_value_col)

min_value_row = np.min(arr2d , axis =1)


min_value_col = np.min(arr2d , axis =0)
print("Minimum value in row:", min_value_row)
print("Minimum value in col:", min_value_col)

44
4. Numpy Array: Numpy Statistical Operations
• Returm the Index of the element that has the largest/smallest value.
• Syntax: np. argmax(arr , [axis] )
• arr: input array np. argmin(arr , [axis] )
[[1, 2, 3],
• axis: search direction axis =0 [4, 5, 6]]
import numpy as np
arr2d = np. array ([[1 , 2, 3], [4, 5, 6]]) axis =1
max_value_row = np.max(arr2d , axis =1)
max_index_row = np.argmax(arr2d , axis =1)
print("Maximum value in row:",max_value_row)
print("Index:", max_index_row) Maximum value in row:[3,6]
Index: [2,2]
max_value_col = np.max(arr2d , axis =0) Maximum value in col:[4,5,6]
max_index_col = np.argmax(arr2d , axis =0) Index: [1,1,1]
print("Maximum value in col:", max_value_col)
print("Index:", max_index_col)
45
4. Numpy Array: Numpy Statistical Operations
• Returm median value in the array.
• Syntax: • array: input array
np.median(array,[axis])
• axis: search direction
[[0, 3, 1],
axis =0 [ 3, 7, 5],
[ 6, 4, 8]] [10, 5, 11]

a b
axis =1

np.median(a) 4.0
np.median(b) 10.0
np.median(a, axis =0) [3.0, 4.0, 5.0]
np.median(a, axis =1) [1.0, 5.0, 6.0]

Python 46
4. Numpy Array: Numpy Statistical Operations

import numpy as np
a = np.array ([[0, 3, 1],
[3, 7, 5],
[6, 4, 8]])

b = [10, 5, 11]

print("Median value in row:", np.median(a , axis =1))


print("Median value in col:", np.median(a , axis =0))
print("Median array A:", np.median(a))
print("Median array B:", np.median(b))

Median value in row: [1., 5., 6.]


Median value in col: [3., 4., 5.]
Median array A: 4.0
Median array B: 10.0
47
4. Numpy Array: Numpy Statistical Operations
• Returm mean value in the array.
• Syntax: • arr: input array
np.mean(array, [axis])
• axis: search direction
[[0, 3, 1],
axis =0 [ 3, 7, 5], [10, 5, 11]
[ 6, 4, 8]]
b
a
axis =1

np.mean(a) 4.11
np.mean(b) 8.66
np.mean(a , axis =0) [3.0, 4.66, 4.66]
np.mean(a , axis =1) [1.33, 5.0, 6.0]

Python 48
4. Numpy Array: Numpy Statistical Operations

import numpy as np
a = np.array ([[0, 3, 1],
[3, 7, 5],
[6, 4, 8]])
Mean_a = 4.11
Mean_b = 8.66
b = [10, 5, 11] Mean_a_axis_0 = [3., 4.66, 4.66]
Mean_a_axis_1 = [1.33, 5., 6. ]
print("Mean_a =", np.mean(a))
print("Mean_b =", np.mean(b))
print("Mean_a_axis_0 =", np.mean(a,axis = 0))
print("Mean_a_axis_1 =", np.mean(a,axis = 1))

49
4. Numpy Array: Numpy Statistical Operations
• Return standard deviation: np.std(array,[axis]) • arr: input array
• Return variance: np.var(array, [axis]) • axis: search direction

[[4, 12, 0, 4],


axis =0 [6, 11, 8, 4],
[18, 14, 13, 7]]

a
axis =1

np.std(a,axis=0) [6.18, 1.24, 5.35, 1.41]


np.std(a,axis=1) [4.35, 2.58, 3.93]
np.var(a,axis=0) [38.22, 1.55, 28.66, 2. ]
np.var(a,axis=1) [19., 6.68, 15.5 ]

50
4. Numpy Array: Numpy Statistical Operations
import numpy as np
a = np.array ([[4, 12, 0, 4],
[6, 11, 8, 4],
[18, 14, 13, 7]])

print("Standard Deviation_a_axis_0 =", np.std(a,axis=0))


print("Standard Deviation_a_axis_1 =", np.std(a,axis=1))
print("Variance_a_axis_0 =", np.var(a,axis=0))
print("Variance_a_axis_1 =", np.var(a,axis=1))

Standard Deviation_a_axis_0 = [6.18, 1.24, 5.35, 1.41]


Standard Deviation_a_axis_1 = [4.35, 2.58, 3.93]
Variance_a_axis_0 = [38.22, 1.55, 28.66, 2. ]
Variance_a_axis_1 = [19. , 6.68, 15.5 ]

51
4. Numpy Array: Numpy Statistical Operations
• Return the elements with conditions where()
arr = 1 2 3 4 5
• Syntax: np. where (condition)
arr >2 F F T T T

result = 3 4 5
import numpy as np

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


result = np.where(arr > 2)
print("Position of elements greater than 2:",result)
print("The value of the elements at the found position:",arr[result])

Position of elements greater than 2: (array([2, 3, 4], dtype=int64),)


The value of the elements at the found position: [3, 4, 5]

52
5. Numpy Linear Algebra
• Linalg: the package in NumPy for Linear Algebra
• dot(): Dot product of two arrays
• vdot(): Return the dot product of two vectors.
• inner(): Inner product of two arrays
• outer(): Compute the outer product of two vectors.
• matmul(): Matrix product of two arrays.
• https://numpy.org/doc/stable/reference/routines.linalg.html

Python 53
5. Numpy Linear Algebra

import numpy as np Dot_Result =


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

b = np.array([[4, 1], Vdot_Result =


[2, 2]]) 6

print("Dot_Result =\n", np.dot(a, b)) Inner_Result =


print("Vdot_Result =\n", np.vdot(a, b)) [[4, 2]
print("Inner_Result =\n", np.inner(a, b)) [1, 2]]
print("Outer_Result =\n", np.outer(a, b))
Outer_Result =
[[4, 1, 2, 2]
[0, 0, 0, 0]
[0, 0, 0, 0]
[4, 1, 2, 2]]

54
6. Numpy Linear Algebra

import numpy as np arr_1:


[[1, 2],
arr_1 = np.array([[1 , 2], [3, 4]]) [3, 4]]
arr_2 = np.array([[5 , 6], [7, 8]])
print("arr_1 :\n", arr_1 ) arr_2:
print("arr_2 :\n", arr_2 ) [[5, 6],
result_matmul = np.matmul(arr_1,arr_2) [7, 8]]
print("Result:\n",result_matmul)
Result:
[[19, 22],
[43, 50]]

Python 55
6. Numpy Linear Algebra
import math Euclicdean Distance Using Python
def Euclicdean_distance(point1, point2):
return math.sqrt((point1[0]-point2[0])**2+ point1[1]-point2[1])**2)
point1 = (1, 2)
point2 = (4, 6)
distance = Euclicdean_distance(point1, point2)
print("Euclicdean distance:", distance)
# Result: Euclicdean distance: 5.0

import numpy as np
def Euclicdean_distance_np(point1, point2):
return np.linalg.norm(np.array(point1)-np.array(point2))
point1 = (1, 2)
point2 = (4, 6)
distance = Euclicdean_distance_np(point1, point2)
print("Euclicdean distance (NumPy):", distance)
# Result: Euclicdean distance (NumPy): 5.0 Euclicdean Distance Using Numpy
56
6. Numpy Linear Algebra
def manhattan_distance(point1, point2): Manhattan Distance Using Python
return sum(abs(a - b) for a, b in zip(point1, point2))
point1 = (1, 2)
point2 = (4, 6)
distance = manhattan_distance(point1, point2)
print("Manhattan distance:", distance)
#Result: Manhattan distance: 7

import numpy as np
def manhattan_distance_np(point1, point2):
return np.sum(np.abs(np.array(point1) - np.array(point2)))
point1 = (1, 2)
point2 = (4, 6)
distance = manhattan_distance_np(point1, point2)
print("Manhattan distance (NumPy):", distance)
# Result: Manhattan distance (NumPy): 7 Manhattan Distance Using NumPy

57
6. Numpy Matrix Library Matlib
• Has functions that return matrices instead of ndarray objects

import numpy as np
import numpy.matlib
#with the specified shape and type without initializing entries
mat_e = np.matlib.empty((3, 2), dtype=int)
#filled with 0
mat_zeros =np.matlib.zeros(5, 3)
#filled with 1
mat_ones = np.matlib.ones(4,3)
#diagonal elements filled with 1, others with 0
mat_ones = np.matlib.eye(3,5)
#create square matrix with 0, diagonal filled with 1, others with 0
mat_zeros = np.matlib.identity(5)
#filled with random data
mat_e = np.matlib.empty(3, 2)

58
7. Input/Output with Numpy

• What are the I/O functions of NumPy?


• The I/O functions provided by NumPy are
• Load() and save() methods handle numPy binary files (with npy extension)
• loadtxt() and savetxt() methods handle normal text files

Python 59
7. Input/Output with Numpy
• Example: The input array is stored in a disk file with the save() method, file
and is loaded by load() method
import numpy as np
a = np.array([1,2,3,4,5])
np.save("out.npy", a)
b = np.load("out.npy")
print(b) [1, 2, 3, 4, 5]
• Example: The input array is stored in a disk file with the savetxt() method, file
and is loaded by loadtxt() method
import numpy as np
a = np.array([1,2,3,4,5])
np.savetxt("out.txt", a)
b = np.loadtxt("out.txt")
print(b) [1., 2., 3., 4., 5.]
Python 60
Practice and exercises

• 1. Practice: Practice all the examples of Chapter 5


• 2. Exercise: in the next slide below

Python 61
Exercises
1. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

a = np.array([1, 2, 3]) # …
print(type(a)) # …
print(a.shape) # …
print(a[0], a[1], a[2]) # …
a[0] = 5 # …
print(a) # …

b = np.array([[1,2,3],[4,5,6]]) # …
print(b.shape) # …
print(b[0, 0], b[0, 1], b[1, 0]) # …

62
Exercises
2. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

a = np.zeros((2,2)) # …
b = np.ones((1,2)) # …
c = np.full((2,2), 7) # …
d = np.eye(2) # …
e = np.random.random((2,2)) # …

63
Exercises
3. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) #...

b = a[:2, 1:3]

print(a[0, 1]) # …

b[0, 0] = 77 # …

print(a[0, 1]) # …

64
Exercises
4. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) #...

row_r1 = a[1, :] # …
row_r2 = a[1:2, :] # …
print(row_r1, row_r1.shape) # …
print(row_r2, row_r2.shape) # …

col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape) # …
print(col_r2, col_r2.shape) # …

65
Exercises
5. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]]) # …

print(a[[0, 1, 2], [0, 1, 0]]) # …

print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # …

print(a[[0, 0], [1, 1]]) # …

print(np.array([a[0, 1], a[0, 1]])) # …

66
Exercises
6. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) #...

print(a) #...

b = np.array([0, 2, 0, 1]) #...

print(a[np.arange(4), b]) # …

a[np.arange(4), b] += 10 #...

print(a) #...

67
Exercises
7. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

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

bool_idx = (a > 2) # …

print(bool_idx) # …

print(a[bool_idx]) # …

print(a[a > 2]) # …

68
Exercises
8. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

x = np.array([1, 2]) # …
print(x.dtype) # …

x = np.array([1.0, 2.0]) # …
print(x.dtype) # …

x = np.array([1, 2], dtype=np.int64) # …


print(x.dtype) # …

69
Exercises
9. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

x = np.array([[1,2],[3,4]], dtype=np.float64) #...


y = np.array([[5,6],[7,8]], dtype=np.float64) #...

print(x + y) #...
print(np.add(x, y)) #...
print(x - y) #...
print(np.subtract(x, y)) #...
print(x * y) #...
print(np.multiply(x, y)) #...
print(x / y) #...
print(np.divide(x, y)) #...
print(np.sqrt(x)) #...
70
Exercises
9. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

x = np.array([[1,2],[3,4]]) #...
y = np.array([[5,6],[7,8]]) #...
v = np.array([9,10]) #...
w = np.array([11, 12]) #...

print(v.dot(w)) #...
print(np.dot(v, w)) #...
print(x.dot(v)) #...
print(np.dot(x, v)) #...
print(x.dot(y)) #...
print(np.dot(x, y)) #...

71
Exercises
10. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

x = np.array([[1,2],[3,4]]) # …

print(np.sum(x)) # …
print(np.sum(x, axis=0)) # …
print(np.sum(x, axis=1)) # …
x = np.array([[1,2], [3,4]])
print(x) # …
print(x.T) # …
v = np.array([1,2,3])
print(v) # …
print(v.T) # …

72
Exercises
11. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

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


v = np.array([1, 0, 1])
y = np.empty_like(x) # …

for i in range(4):
y[i, :] = x[i, :] + v

print(y) #...

73
Exercises
11. Explain the meaning of each command line and show the result of the
following code:
import numpy as np
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
vv = np.tile(v, (4, 1)) # …
print(vv) # …
y = x + vv # …
print(y) # …
12. Explain the meaning of each command line and show the result of the
following code:
import numpy as np
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v # …
print(y) # …
74
Exercises
13. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

# Compute outer product of vectors


v = np.array([1,2,3]) # v has shape (3,)
w = np.array([4,5]) # w has shape (2,)
print(np.reshape(v, (3, 1)) * w) #...

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


print(x + v) #...

print((x.T + w).T)#...
print(x + np.reshape(w, (2, 1)))#...

75
Exercises
14. Explain the meaning of each command line and show the result of the
following code:
import numpy as np

v = np.array([1,2,3]) # …
w = np.array([4,5]) # …
print(np.reshape(v, (3, 1)) * w) # …

x = np.array([[1,2,3], [4,5,6]]) # …
print(x + v) # …

print((x.T + w).T) # …
print(x + np.reshape(w, (2, 1))) # …

print(x * 2) # …

76
The end of Chapter

77

You might also like