Chapter 5. Numeric Computing with Numpy (1)
Chapter 5. Numeric Computing with Numpy (1)
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_
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])
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
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]]
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
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]])
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]]
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]]
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))
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]]
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)
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]
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
a
axis =1
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]])
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
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
54
6. Numpy Linear Algebra
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
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
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
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
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
66
Exercises
6. Explain the meaning of each command line and show the result of the
following code:
import numpy as np
print(a) #...
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
bool_idx = (a > 2) # …
print(bool_idx) # …
print(a[bool_idx]) # …
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) # …
69
Exercises
9. Explain the meaning of each command line and show the result of the
following code:
import numpy as np
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
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
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