Python_Numpy
Python_Numpy
[ ]: import numpy as np
[ ]: import numpy as np
print(np.__version__)
print(np.show_config())
1.22.4
openblas64__info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),
('HAVE_BLAS_ILP64', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
blas_ilp64_opt_info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),
('HAVE_BLAS_ILP64', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
openblas64__lapack_info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),
1
('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
lapack_ilp64_opt_info:
libraries = ['openblas64_', 'openblas64_']
library_dirs = ['/opt/arm64-builds/lib']
language = c
define_macros = [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'),
('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)]
runtime_library_dirs = ['/opt/arm64-builds/lib']
Supported SIMD extensions in this NumPy install:
baseline = NEON,NEON_FP16,NEON_VFPV4,ASIMD
found = ASIMDHP
not found = ASIMDDP
None
[ ]: # one-dimensional array
one_arr = np.array([1, 2, 3, 4, 5])
print("One-dimensional NumPy array: ",one_arr)
l = [1, 2, 3, 4]
print("Original List:",l)
list_arr = np.array(l)
print("One-dimensional NumPy array from a given numeric list: ",list_arr)
# two-dimensional array
two_arr=arr = np.array([[1, 2, 3], [4, 5, 6]])
# from a list of lists
listOfLists = [[1, 2, 3], [4, 5, 6], [7,8,9]]
print("Original list of lists: ",listOfLists)
list2_arr = np.array(listOfLists)
print("Two-dimensional NumPy array from list of two lists : \n",list2_arr)
2
1.2.2 Write a program to convert a list and tuple into Numpy arrays
Hint: Use the function asarray()
[ ]: my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array: ")
print(np.asarray(my_list))
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Tuple to array: ")
print(np.asarray(my_tuple))
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]
[ ]: x = np.ones((5,5))
print("Original array:")
print(x)
print("Output array with 1 on the border and 0 inside in the array")
x[1:-1,1:-1] = 0
print(x)
Original array:
[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]
Output array with 1 on the border and 0 inside in the array
[[1. 1. 1. 1. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 1. 1. 1. 1.]]
3
1.2.4 Write a program to create a 3x3 matrix with values ranging from 1 to 9
[ ]: x = np.arange(1, 10).reshape(3,3)
print(x)
[[1 2 3]
[4 5 6]
[7 8 9]]
1.2.5 Write a program to create a 8x8 matrix and fill it with a checkerboard pattern
filled with 0 and 1.
[ ]: print("Checkerboard pattern:")
x = np.zeros((8,8),dtype=int)
x[1::2,::2] = 1
x[::2,1::2] = 1
print(x)
Checkerboard pattern:
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
1.2.6 Write a program to create a 8x8 matrix and fill it with a checkerboard pattern
filled with 0 and 1 using the function tile ()
[ ]: print("Checkerboard pattern:")
x = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(x)
Checkerboard pattern:
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
4
1.2.7 Write a program to create a null vector of size 10 and update sixth value to 11.
[ ]: x = np.zeros(10)
print(x)
print("Update sixth value to 11")
x[6] = 11
print(x)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Update sixth value to 11
[ 0. 0. 0. 0. 0. 0. 11. 0. 0. 0.]
1.2.9 Write a NumPy program to create a 3-D array with ones on a diagonal and
zeros elsewhere.
[ ]: import numpy as np
x = np.eye(3)
print(x)
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
5
1.3 Subsetting/Slicing/Indexing
1.3.1 Create an arrary as follows:
• Return the array of elements in the 2nd row
• Return the array of elements in the third column
• Return a sub-array consisting of the odd rows and even columns of.
[ ]: import numpy
Y = numpy.array([
[3,6,9,12],
[15,18,21,24],
[27,30,33,36],
[39,42,45,48],
[51,54,57,60]
])
Y[::2, 1::2]
[ ]: array([[ 6, 12],
[30, 36],
[54, 60]])
[ ]: import numpy as np
A = np.array([3,4,6,10,24,89,45,43,46,99,100])
div3 = A[A%3!=0]
print("Elements of A not divisible by 3:")
print(div3)
div5 = A[A%5==0]
print("Elements of A divisible by 5:")
print(div5)
print("Elements of A, which are divisible by 3 and 5:")
print(A[(A%3==0) & (A%5==0)])
print("------------------")
A[A%3==0] = 42
print("""New values of A after setting the elements of A,
which are divisible by 3, to 42:""")
print(A)
6
Elements of A, which are divisible by 3 and 5:
[45]
------------------
New values of A after setting the elements of A,
which are divisible by 3, to 42:
[ 42 4 42 10 42 89 42 43 46 42 100]
1.4 Broadcasting
1.4.1 Write a NumPy program to broadcast on different shapes of arrays where p(3,3)
+ q(3). The p variable has a shape of (3, 3), while q only has a shape of 3.
[ ]: import numpy as np
p = np.array([[0, 0, 0],
[1, 2, 3],
[4, 5, 6]])
q= np.array([10, 11, 12])
print("Original arrays:")
print("Array-1")
print(p)
print("Array-2")
print(q)
print("\nNew Array:")
new_array1 = p + q
print(new_array1)
1.4.2 Selling pies on weekends. Sell 3 types of pies at different prices, and the following
number of each pie was sold last weekend. How much money I made per pie
type per day? Requirement: Don’t use loops
7
print("\nPie sales (#):")
print(sales)
Pie cost:
[20 15 25]
or
8
[]: array([[ 40, 60, 20],
[ 90, 45, 45],
[125, 75, 125]])
[ ]: x = np.arange(1, 10)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x)
Original array:
[1 2 3 4 5 6 7 8 9]
Reverse array:
[9 8 7 6 5 4 3 2 1]
[ ]: x = np.arange(1, 10)
print("Original array")
print(x)
x = np.asfarray(x)
print("Array converted to a float type:")
print(x)
9
Original array
[1 2 3 4 5 6 7 8 9]
Array converted to a float type:
[1. 2. 3. 4. 5. 6. 7. 8. 9.]
1.6.3 Write a program to test whether each element of a 1-D array is also present in
a second array
Example: Array1: [ 0, 1, 2, 3, 5] and Array2: [0, 2, 4]
Compare each element of Array1 and Array2: [ True False False True False]
Hint: Use the function in1d()
Array1: [0 1 2 3 5]
Array2: [0, 2, 4]
Compare each element of array1 and array2
[ True False True False False]
1.6.4 Write a program to find common values between two Numpy arrays.
Example: Array1: [ 0 10 20 40 60] and Array2: [10, 30, 40]
Common values between two arrays:[10 40]
Hint: Use the function intersec1d()
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]
10
• mod
• remainder
11
[ -7 -6 -5]
[ -4 -3 -2]]
Multiplying the two arrays:
[[ 0 10 20]
[30 40 50]
[60 70 80]]
Dividing the two arrays:
[[0. 0.1 0.2]
[0.3 0.4 0.5]
[0.6 0.7 0.8]]
calculating exponents of an array of numbers:
[125 27 216 729 8 64]
Use numpy.reciprocal() function
[0.02 0.74626866 0.33333333 1. 0.04 ]
Use numpy.reciprocal() function
[0]
Use numpy.mod() function
[3 0 1]
Use numpy.remainder() function
[3 0 1]
[ ]: import numpy as np
A = np.array([[6, 1, 1],
[4, -1, 6],
[4, 8, 9]])
# Rank of a matrix
print("Rank of A:", np.linalg.matrix_rank(A))
# Trace of matrix A
print("\nTrace of A:", np.trace(A))
# Determinant of a matrix
print("\nDeterminant of A:", np.linalg.det(A))
# Inverse of matrix A
print("\nInverse of A:\n", np.linalg.inv(A))
Rank of A: 3
Trace of A: 11
12
Determinant of A: -306.0
Inverse of A:
[[ 0.17647059 -0.00326797 -0.02287582]
[ 0.05882353 -0.13071895 0.08496732]
[-0.11764706 0.1503268 0.05228758]]
[ ]: a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
print("Dot product: ")
print(np.dot(a,b))
print("Complex-conjugating dot product: ")
np.vdot(a,b)
Dot product:
[[37 40]
[85 92]]
Complex-conjugating dot product:
[ ]: 130
[ ]: 2
[ ]: (2, 3)
13
[ ]: #Some multidimensional examples:
#Example 2
a = np.arange(2).reshape((1,1,2))
b = np.arange(6).reshape((3,2))
c = np.inner(a, b)
c.shape
[ ]: (1, 1, 3)
[ ]: #Example 1
rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
rl
im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
im
grid = rl + im
grid
[ ]: #Example 2
x = np.array(['a', 'b', 'c'], dtype=object)
np.outer(x, [1, 2, 3])
[ ]: #Example 1:
a = np.ones([9, 5, 7, 4])
b = np.ones([9, 5, 4, 3])
np.dot(a, b).shape
np.matmul(a, b).shape
[ ]: (9, 5, 7, 3)
[ ]: #Example 2:
a = [[1,0],[0,1]]
b = [1,2]
print (np.matmul(a,b))
print (np.matmul(b,a))
14
[1 2]
[1 2]
[ ]: #Example 3:
import numpy.matlib
import numpy as np
a = np.arange(8).reshape(2,2,2)
b = np.arange(4).reshape(2,2)
print (np.matmul(a,b))
[[[ 2 3]
[ 6 11]]
[[10 19]
[14 27]]]
2 DO IT YOURSELF
2.1 Create the following arrays:
• Create an array of 5 zeros.
• Create an array of 10 ones.
• Create an array of 5 3.141s.
• Create an array of the integers 1 to 20.
• Create a 5 x 5 matrix of ones with a dtype int.
2.4 Write expressions to extract the following sub-arrays of a 6x6 random array
with:
• rows 0, 1, and 2.
• rows 0, 1, and 5.
• columns 0, 1, and 2.
• columns 0, 1, and 3
• columns 0, 1, and 2 from rows 2 and 3.
• consisting of the odd rows and even columns
15
2.5 Write a program to create a 2d Numpy array as below:
[[0. 0. 0. 0. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 0. 0. 0. 0.]]
2.6 Run the following code to create an array of shape 4 x 4 and then use
indexing to produce the outputs shown below.
[]: import numpy as np
a = np.arange(1, 26).reshape(5, -1)
[ ]: 20
[ ]: # your answer
[ ]: array([[ 9, 10],
[14, 15],
[19, 20],
[24, 25]])
[ ]: # your answer
[ ]: array([ 6, 7, 8, 9, 10])
[ ]: # your answer
[ ]: # your answer
[ ]: array([[ 8, 9],
[13, 14]])
[ ]: # your answer
[ ]: # your answer
[ ]: # your answer
16
[ ]: # your answer
2.8 Find the location of the minimum value in the following array b:
Hint: Use the function argmin()
[]: np.random.seed(123)
b = np.random.randn(10)
b
2.9 Generate a 10 x 3 array of random numbers (in range [0,1]). For each row,
pick the number closest to 0.5.
• Use abs and argsort to find the column j closest for each row.
• Use fancy indexing to extract elements in the rows [0,1,2] and in the columns [2,3,1]
17
2.10 The array named pos has a shape of (6,2). Consider each row of pos is
used to store the position of an object. For example, pos[0,0] and pos[0,1]
store, respectively, the x- and y-coordinates of the first object. The array
elements ref [0] and ref [1] store, respectively, the x- and y-coordinates of
a reference point. The task is to compute the distance between each of
the 6 objects in pos from the reference point ref. This task is required
to complete using numpy functions and arithmetic operators. If the co-
ordinates of the object is (x,y) and those of the reference
p point are (a,b),
then their distance is given by the formula: (x − a)2 + (y − b)2 . Two
numpy arrays pos and ref are given as follows:
[ ]: pos = np.array([[ 1.72, 2.56],
[ 0.24, 5.67],
[ -1.24, 5.45],
[ -3.17, -0.23],
[ 1.17, -1.23],
[ 1.12, 1.08]])
Hints: Use numpy broadcasting and some numpy mathematical functions (https://numpy.org/
doc/stable/reference/routines.math.html)
2.11 Create a two demensions array and make some statistic computation on
this array
[[45 61 65 44 1 18]
[ 7 4 58 58 66 78]
[16 95 39 1 90 33]
[40 41 79 67 40 86]]
The output results are presented as below:
* Min value for rows : [ 1 4 1 40]
* Min value for columns : [ 7 4 39 1 1 18]
* Max value for rows : [65 78 95 86]
* Max value for columns : [45 95 79 67 90 86]
- Min value of ARRAY : 1
- Max value of ARRAY : 95
- Mean value for rows : [39. 45.16666667 45.66666667 58.83333333]
- Mean value for rows : [27. 50.25 60.25 42.5 49.25 53.75]
- Mean value of ARRAY : 47.166666666666664
- StDeviation value for rows : [22.75228926 28.84681766 35.30659366 19.31680328]
- StDeviation value for columns : [15.92168333 32.94977238 14.41136704 25.32291452 32.99526481
- StDeviation value of ARRAY : 28.18933998675543
- Variance value for rows : [ 517.66666667 832.13888889 1246.55555556 373.13888889]
- Variance value for columns : [ 253.5 1085.6875 207.6875 641.25 1088.6875 834.1875]
- Variance value for ARRAY : 794.6388888888888
18
2.12 Write a function which takes two arrays of equal size and returns a array
of the same size where the ith element is True if the ith elements of the
two arrays are equal.
Example: given the arrays np.array([10, 20, 30]) and np.array([10, 30, 30]), the function
would return np.array([True, False, True]). Requirement: uses NumPy
Hint: Use the function where()
arrays and functions.
2.13 Write a function which takes two arrays of equal length and returns an
array of the indices where the elements of the two arrays are equal.
Example: given the arrays np.array([10, 20, 30]) and np.array([10, 30, 30]), the function
would return np.array([0, 2]).
Requirement: uses NumPy arrays and functions.
Hint: Use the function where()
2.16 Check the answer by multiplying the matrix A by the solution vector x,
subtract the vector b. Print the difference vector. Then take the Euclidean
norm (length) of the difference vector. That is, calculate d = Ax-b and
|d| = |Ax - b|.
Hint: Don’t use * when multiplying matrix with a vector. Use the np.dot function instead.
19
2.17 Write a function add_row(A,s,i,j) that takes as input parameters a numpy
array representing the matrix A , a number s , and integers i and j and
returns the numpy array resulting from adding s times i row to j row.
Do not need to check whether the indices and are valid, but should make
sure that the output is correct for i =j.
2.18 Write a function inverse_matrix(A) that computes the inverse of a matrix
using Gauss elimination.
Hint : Assume that the matrix is invertible.
2.20 Write a NumPy program to compute the sum of the diagonal element of
a given array
Hint: Use numpy.trace()
2.21 Write a NumPy program to compute the eigenvalues and right eigenvec-
tors of a given square array
Hint: Use numpy.linalg.eig()
More information: https://mathworld.wolfram.com/Eigenvalue.html
20