# The first step of using numpy is to tell python to import it
import numpy as np
# defining a list of different car companies or string elements
arr_str = ['Mercedes', 'BMW', 'Audi', 'Ferrari', 'Tesla']
# defining a list of number of cylinders in car or numerical elements
arr_num = [5, 4, 6, 7, 3]
# connverting the list arr_str to a NumPy array
np_arr_str = np.array(arr_str)
# connverting the list arr_num to a NumPy array
np_arr_num = np.array(arr_num)
# checking the output
print('Numpy Array (arr_str): ',np_arr_str)
print('Numpy Array (arr_num): ',np_arr_num)
Numpy Array (arr_str): ['Mercedes' 'BMW' 'Audi' 'Ferrari' 'Tesla']
Numpy Array (arr_num): [5 4 6 7 3]
The resuts look similar to a list but arr_str and arr_num have been converted to NumPy arrays. Let's check the data type to confirm this.
# printing the data type of lists
print('Data type of arr_str: ',type(arr_str))
print('Data type of arr_num: ',type(arr_num))
# printing the data type after conversion of lists to array
print('Data type of np_arr_str: ',type(np_arr_str))
print('Data type of np_arr_num: ',type(np_arr_num))
Data type of arr_str: <class 'list'>
Data type of arr_num: <class 'list'>
Data type of np_arr_str: <class 'numpy.ndarray'>
Data type of np_arr_num: <class 'numpy.ndarray'>
# let's say we have information of different number of cylinders in a car and we want to
matrix = np.array([[1,2,1],[4,5,9],[1,8,9]])
print(matrix)
[[1 2 1]
[4 5 9]
[1 8 9]]
print('Data type of matrix: ',type(matrix))
Data type of matrix: <class 'numpy.ndarray'>
There are different ways to create NumPy arrays using the functions available in NumPy library
Using np.arange() function
arr2 = np.arange(start = 0, stop = 10) # 10 will be excluded from the output
print(arr2)
# or
arr2 = np.arange(0,10)
print(arr2)
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
# adding a step size of 5 to create an array
arr3 = np.arange(start = 0, stop = 20, step = 5)
arr3
Output:
array([ 0, 5, 10, 15])
Using np.linspace() function
matrix2 = np.linspace(0,5) # by default 50 evenly spaced values will be generated betwee
matrix2
Output:
array([0. , 0.10204082, 0.20408163, 0.30612245, 0.40816327,
0.51020408, 0.6122449 , 0.71428571, 0.81632653, 0.91836735,
1.02040816, 1.12244898, 1.2244898 , 1.32653061, 1.42857143,
1.53061224, 1.63265306, 1.73469388, 1.83673469, 1.93877551,
2.04081633, 2.14285714, 2.24489796, 2.34693878, 2.44897959,
2.55102041, 2.65306122, 2.75510204, 2.85714286, 2.95918367,
3.06122449, 3.16326531, 3.26530612, 3.36734694, 3.46938776,
3.57142857, 3.67346939, 3.7755102 , 3.87755102, 3.97959184,
4.08163265, 4.18367347, 4.28571429, 4.3877551 , 4.48979592,
4.59183673, 4.69387755, 4.79591837, 4.89795918, 5. ])
The step size or the difference between each element will be decided by the following formula:
(stop - start) / (total elements - 1)
So, in this case: (5 - 0) / 49 = 0.10204082
The first value will be 0.10204082, the second value will be 0.10204082 + 0.10204082, the third value will be 0.10204082 + 0.10204082 +0.10204082, and so on.
# generating 10 evenly spaced values between 10 and 20
matrix3 = np.linspace(10,20,10)
matrix3
Output:
array([10. , 11.11111111, 12.22222222, 13.33333333, 14.44444444,
15.55555556, 16.66666667, 17.77777778, 18.88888889, 20. ])
Similarly we can create matrices using the functions available in NumPy library
Using np.zeros()
matrix4 = np.zeros([3,5])
matrix4
Output:
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
Using np.ones()
matrix5 = np.ones([3,5])
matrix5
Output:
array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
Using np.eye()
matrix6 = np.eye(5)
matrix6
Output:
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
We can also convert a one dimension array to a matrix. This can be done by using the np.reshape() function.
# defining an array with values 0 to 9
arr4 = np.arange(0,10)
arr4
Output:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# reshaping the array arr4 to a 2 x 5 matrix
arr4_reshaped = arr4.reshape((2,5))
arr4_reshaped
Output:
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
arr4
Output:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# reshaping the array arr4 to a 2 x 6 matrix
arr4.reshape((2,6))
NumPy can also perform a large number of different mathematical operations and it provides different functions to do so.
NumPy provides:
1. Trigonometric functions
2. Exponents and Logarithmic functions
3. Functions for arithmetic operations between arrays and matrices
print('Sine Function:',np.sin(4))
print('Cosine Function:',np.cos(4))
print('Tan Function',np.tan(4))
Sine Function: -0.7568024953079282
Cosine Function: -0.6536436208636119
Tan Function 1.1578212823495777
Exponents and Logarithmic functions
• Exponents
np.exp(2)
Output:
7.38905609893065
arr5 = np.array([2,4,6])
np.exp(arr5)
Output:
array([ 7.3890561 , 54.59815003, 403.42879349])
• Logarithms
# by default NumPy takes the base of log as e
np.log(2)
Output:
0.6931471805599453
np.log(arr5)
Output:
array([0.69314718, 1.38629436, 1.79175947])
## log with base 10
np.log10(8)
Output:
0.9030899869919435
# arithmetic on lists
l1 = [1,2,3]
l2 = [4,5,6]
print(l1+l2)
# this does not behave as you would expect!
[1, 2, 3, 4, 5, 6]
# we can +-*/ arrays together
# defining two arrays
arr7 = np.arange(1,6)
print('arr7:', arr7)
arr8 = np.arange(3,8)
print('arr8:', arr8)
arr7: [1 2 3 4 5]
arr8: [3 4 5 6 7]
print('Addition: ',arr7+arr8)
print('Subtraction: ',arr8-arr7)
print('Multiplication:' , arr7*arr8)
print('Division:', arr7/arr8)
print('Inverse:', 1/arr7)
print('Powers:', arr7**arr8) # in python, powers are achieved using **, NOT ^!!! ^ does
Addition: [ 4 6 8 10 12]
Subtraction: [2 2 2 2 2]
Multiplication: [ 3 8 15 24 35]
Division: [0.33333333 0.5 0.6 0.66666667 0.71428571]
Inverse: [1. 0.5 0.33333333 0.25 0.2 ]
Powers: [ 1 16 243 4096 78125]
matrix7 = np.arange(1,10).reshape(3,3)
print(matrix7)
matrix8 = np.eye(3)
print(matrix8)
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
print('Addition: \n', matrix7+matrix8)
print('Subtraction: \n ', matrix7-matrix8)
print('Multiplication: \n', matrix7*matrix8)
print('Division: \n', matrix7/matrix8)
Addition:
[[ 2. 2. 3.]
[ 4. 6. 6.]
[ 7. 8. 10.]]
Subtraction:
[[0. 2. 3.]
[4. 4. 6.]
[7. 8. 8.]]
Multiplication:
[[1. 0. 0.]
[0. 5. 0.]
[0. 0. 9.]]
Division:
[[ 1. inf inf]
[inf 5. inf]
[inf inf 9.]]
C:\Users\javab\AppData\Local\Temp\ipykernel_13344\2604038799.py:4: Runtim
eWarning: divide by zero encountered in true_divide
print('Division: \n', matrix7/matrix8)
matrix9 = np.arange(1,10).reshape(3,3)
print('First Matrix: \n',matrix9)
matrix10 = np.arange(11,20).reshape(3,3)
print('Second Matrix: \n',matrix10)
print('')
# taking linear algebra matrix multiplication (some may have heard this called the dot p
print('Multiplication: \n', matrix9 @ matrix10)
First Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Second Matrix:
[[11 12 13]
[14 15 16]
[17 18 19]]
Multiplication:
[[ 90 96 102]
[216 231 246]
[342 366 390]]
print(matrix9)
[[1 2 3]
[4 5 6]
[7 8 9]]
# taking transpose of matrix
np.transpose(matrix9)
Output:
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
# another way of taking a transpose
matrix9.T
Output:
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
Function to find minimum and maximum values
print(matrix9)
[[1 2 3]
[4 5 6]
[7 8 9]]
print('Minimum value: ',np.min(matrix9))
Minimum value: 1
print('Maximum value: ',np.max(matrix9))
Maximum value: 9
Function to generate random samples
Using np.random.rand function
# Generating random values in an array
rand_mat = np.random.rand(5)
print(rand_mat)
[0.20348605 0.06874522 0.11855155 0.9515906 0.06792922]
# * Generating random values in a matrix
rand_mat = np.random.rand(5,5) # uniform random variable
print(rand_mat)
[[0.75389798 0.73097922 0.18855201 0.81265649 0.19205387]
[0.42578218 0.50920319 0.34132995 0.20459155 0.59114447]
[0.74891893 0.00773198 0.9172758 0.33114609 0.44197677]
[0.66871854 0.60355637 0.95413401 0.3438613 0.84489469]
[0.94538656 0.17640361 0.73733783 0.99773803 0.94548552]]
Using np.random.randn function
# Generating random values in an array
rand_mat2 = np.random.randn(5)
print(rand_mat2)
[-1.46121271 -1.54537319 -1.68549242 1.81322879 -0.51425932]
# Generating random values in a matrix
rand_mat2 = np.random.randn(5,5)
print(rand_mat2)
[[-0.50492381 0.92563043 -1.24745144 0.71834587 0.24044178]
[ 2.2683284 0.13502434 0.20326969 1.14625927 -0.22091927]
[-0.89041308 -0.15083257 -0.16754162 0.63558927 0.6742062 ]
[ 0.23813842 -1.62703826 2.08191694 -0.34173192 -1.24531203]
[ 0.39476176 -0.08516735 1.09735189 -1.71800456 0.53239333]]
# Let's check the mean and standard deviation of rand_mat2
print('Mean:',np.mean(rand_mat2))
print('Standard Deviation:',np.std(rand_mat2))
Mean: 0.1236928667643414
Standard Deviation: 0.9886789413697564
Using np.random.randint function
# Generating random values in an array
rand_mat3 = np.random.randint(1,5,10)
print(rand_mat3)
[3 2 3 1 2 4 3 3 4 4]
# Generating random values in a matrix
rand_mat3 = np.random.randint(1,10,[5,5])
print(rand_mat3)
[[1 5 2 1 2]
[6 1 7 1 8]
[6 6 5 2 5]
[4 3 7 3 1]
[2 6 1 1 5]]
# let's generate an array with 10 random values
rand_arr = np.random.randn(10)
print(rand_arr)
[ 0.14625935 0.36198003 0.5429037 0.34820694 -0.11581811 1.44909754 0.97508681 0.28135544 -0.00682169 0.64570711]
# accessing the 6 th entry of rand_arr
print(rand_arr[6])
0.9750868051863055
# we can access multiple entries at once using
print(rand_arr[4:9])
[-0.11581811 1.44909754 0.97508681 0.28135544 -0.00682169]
# we can also access multiple non-consecutive entries using np.arange
print('Index of values to access: ',np.arange(3,10,3))
print(rand_arr[np.arange(3,10,3)])
Index of values to access: [3 6 9]
[ 1.69663775 -0.58451129 0.52114238]
print(rand_arr)
[-0.61610084 0.256255 -1.02474372 1.69663775 0.14830608 0.0587465
-0.58451129 0.09827507 1.38926594 0.52114238]
rand_arr>0
Output:
array([False, True, False, True, True, True, False, True, True, True])
# accessing all the values of rand_arr which are greater than 0
print('Values greater than 0: ',rand_arr[rand_arr>0])
# accessing all the values of rand_arr which are less than 0
print('Values less than 0: ',rand_arr[rand_arr<0])
Values greater than 0: [0.256255 1.69663775 0.14830608 0.0587465 0.09
827507 1.38926594
0.52114238]
Values less than 0: [-0.61610084 -1.02474372 -0.58451129]
# let's generate an array with 10 random values
rand_mat = np.random.randn(5,5)
print(rand_mat)
[[ 0.66008467 -0.91860835 -0.91768744 -0.56565779 -0.19013084]
[ 0.68692112 1.20042327 -0.55648032 0.51675983 -1.13325252]
[ 1.76883638 -0.85498119 1.89998922 -1.0658905 1.50531893]
[ 0.77388464 -1.24206763 0.75631041 1.01940576 0.89747448]
[ 0.37852758 -1.36846366 -0.91566544 -0.47943544 -0.20226054]]
# acessing the second row of the rand_mat
rand_mat[1]
Output:
array([ 0.68692112, 1.20042327, -0.55648032, 0.51675983, -1.13325252])
# acessing third element of the second row
print(rand_mat[1][2])
#or
print(rand_mat[1,2])
-0.5564803167132045
-0.5564803167132045
# accessing first two rows with second and third column
print(rand_mat[0:2,1:3])
[[-0.91860835 -0.91768744]
[ 1.20042327 -0.55648032]]
print(rand_mat)
[[ 0.66008467 -0.91860835 -0.91768744 -0.56565779 -0.19013084]
[ 0.68692112 1.20042327 -0.55648032 0.51675983 -1.13325252]
[ 1.76883638 -0.85498119 1.89998922 -1.0658905 1.50531893]
[ 0.77388464 -1.24206763 0.75631041 1.01940576 0.89747448]
[ 0.37852758 -1.36846366 -0.91566544 -0.47943544 -0.20226054]]
# accessing all the values of rand_mat which are greater than 0
print('Values greater than 0: \n ',rand_mat[rand_mat>0])
# accessing all the values of rand_mat which are less than 0
print('Values less than 0: \n',rand_mat[rand_mat<0])
Values greater than 0:
[0.66008467 0.68692112 1.20042327 0.51675983 1.76883638 1.89998922
1.50531893 0.77388464 0.75631041 1.01940576 0.89747448 0.37852758]
Values less than 0:
[-0.91860835 -0.91768744 -0.56565779 -0.19013084 -0.55648032 -1.13325252
-0.85498119 -1.0658905 -1.24206763 -1.36846366 -0.91566544 -0.47943544
-0.20226054]
print(rand_arr)
[-0.61610084 0.256255 -1.02474372 1.69663775 0.14830608 0.0587465
-0.58451129 0.09827507 1.38926594 0.52114238]
# let's change some values in an array!
# changing the values of index value 3 and index value 4 to 5
rand_arr[3:5] = 5
print(rand_arr)
[-0.61610084 0.256255 -1.02474372 5. 5. 0.0587465
-0.58451129 0.09827507 1.38926594 0.52114238]
# changing the values of index value 0 and index value 1 to 2 and 3 respectively
rand_arr[0:2] = [2,3]
print(rand_arr)
[ 2. 3. -1.02474372 5. 5. 0.0587465
-0.58451129 0.09827507 1.38926594 0.52114238]
# modify entries using logical references
rand_arr[rand_arr>0] = 65
rand_arr
Output:
array([65. , 65. , -1.02474372, 65. , 65. ,
65. , -0.58451129, 65. , 65. , 65. ])
print(rand_mat3)
[[1 5 2 1 2]
[6 1 7 1 8]
[6 6 5 2 5]
[4 3 7 3 1]
[2 6 1 1 5]]
# changing the values of the 4th and 5th element of the second and third rows of the mat
print('Matrix before modification: \n',rand_mat3)
rand_mat3[1:3,3:5] = 0
print('Matrix after modification: \n',rand_mat3)
Matrix before modification:
[[1 5 2 1 2]
[6 1 7 1 8]
[6 6 5 2 5]
[4 3 7 3 1]
[2 6 1 1 5]]
Matrix after modification:
[[1 5 2 1 2]
[6 1 7 0 0]
[6 6 5 0 0]
[4 3 7 3 1]
[2 6 1 1 5]]
# extracting the first 2 rows and first 3 columns from the matrix
sub_mat = rand_mat[0:2,0:3]
print(sub_mat)
[[ 0.66008467 -0.91860835 -0.91768744]
[ 0.68692112 1.20042327 -0.55648032]]
# changing all the values of the extracted matrix to 3
sub_mat[:] = 3
print(sub_mat)
[[3. 3. 3.]
[3. 3. 3.]]
# what happened to rand_mat when we change sub_mat?
rand_mat
Output:
array([[ 3. , 3. , 3. , -0.56565779, -0.19013084],
[ 3. , 3. , 3. , 0.51675983, -1.13325252],
[ 1.76883638, -0.85498119, 1.89998922, -1.0658905 , 1.50531893],
[ 0.77388464, -1.24206763, 0.75631041, 1.01940576, 0.89747448],
[ 0.37852758, -1.36846366, -0.91566544, -0.47943544, -0.2022605
4]])
# to prevent this behavior we need to use the .copy() method when we assign sub_mat
# this behavior is the source of MANY errors for early python users!!!
rand_mat = np.random.randn(5,5)
print(rand_mat)
sub_mat = rand_mat[0:2,0:3].copy()
sub_mat[:] = 3
print(sub_mat)
print(rand_mat)
[[ 2.0112384 0.49785818 -1.25183808 1.68261636 0.51405209]
[ 0.19861572 -1.02405923 1.47588997 0.9095827 1.44913937]
[ 1.17797906 2.2230628 1.0897073 -0.61658736 1.30247375]
[-0.72899737 0.35296055 -1.28267073 -0.12390565 0.74816716]
[ 1.54172729 0.23114564 -0.06203034 -0.00718632 -0.32182532]]
[[3. 3. 3.]
[3. 3. 3.]]
[[ 2.0112384 0.49785818 -1.25183808 1.68261636 0.51405209]
[ 0.19861572 -1.02405923 1.47588997 0.9095827 1.44913937]
[ 1.17797906 2.2230628 1.0897073 -0.61658736 1.30247375]
[-0.72899737 0.35296055 -1.28267073 -0.12390565 0.74816716]
[ 1.54172729 0.23114564 -0.06203034 -0.00718632 -0.32182532]]
Let's save some NumPy objects on the disk for use later!
from google.colab import drive
drive.mount('/content/drive')
Mounted at /content/drive
# creating a random matrices
randint_matrix1 = np.random.randint(1,10,10).reshape(2,5)
print(randint_matrix1)
print('')
randint_matrix2 = np.random.randint(10,20,10).reshape(2,5)
print(randint_matrix2)
[[7 2 9 7 2]
[6 6 5 7 2]]
[[10 16 12 17 18]
[19 12 11 13 17]]
np.save('/content/drive/MyDrive/Python Course/saved_file_name',randint_matrix1)
np.savez('/content/drive/MyDrive/Python Course/multiple_files',randint_matrix1=randint_m
# now let's load it
loaded_arr = np.load('/content/drive/MyDrive/Python Course/saved_file_name.npy')
loaded_multi = np.load('/content/drive/MyDrive/Python Course/multiple_files.npz')
print(loaded_arr)
print('')
print(loaded_multi)
print('1st Matrix: \n',loaded_multi['randint_matrix1'])
print('2nd Matrix: \n',loaded_multi['randint_matrix2'])
new_matrix = loaded_multi['randint_matrix1']
print('New Matrix: \n',new_matrix)
# we can also save/load text files...but only single variables
np.savetxt('/content/drive/MyDrive/Python Course/text_file_name.txt',randint_matrix1,del
rand_mat_txt = np.loadtxt('/content/drive/MyDrive/Python Course/text_file_name.txt',deli
print(randint_matrix1)
print('')
print(rand_mat_txt)
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc