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

numpy

The document contains a series of exercises focused on using the NumPy library for various array manipulations and mathematical operations. Each exercise provides code snippets that demonstrate how to create, reshape, and perform calculations on arrays, including operations like matrix multiplication, normalization, and finding unique values. The exercises are designed to help users practice and understand fundamental concepts in machine learning and data manipulation using NumPy.

Uploaded by

yeshw537
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

numpy

The document contains a series of exercises focused on using the NumPy library for various array manipulations and mathematical operations. Each exercise provides code snippets that demonstrate how to create, reshape, and perform calculations on arrays, including operations like matrix multiplication, normalization, and finding unique values. The exercises are designed to help users practice and understand fundamental concepts in machine learning and data manipulation using NumPy.

Uploaded by

yeshw537
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Machine Learning

Laboratory

S.Yeshwanth,
23N266

23N266, pg. 1
Importing numpy

import numpy as np

Exercise 1:

Create a 1D array with values ranging from 0 to 9.

import numpy as np
nums = np.arange(10)
nums
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Exercise 2:

Convert a 1D array to a 2D array with 2 rows.

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

array([[1, 2, 3],
[4, 5, 6]])

Exercise 3:

Multiply a 5x3 matrix by a 3x2 matrix.

arr1 = np.arange(15).reshape((5,3))
arr2 = np.arange(6).reshape((3,2))

prod = np.dot(arr1, arr2)

print("Arr1: ",arr1)
print("Arr2: ",arr2)
print("Prod: ",prod)

Arr1: [[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
Arr2: [[0 1]
[2 3]
[4 5]]
Prod: [[ 10 13]
[ 28 40]
[ 46 67]

23N266, pg. 2
[ 64 94]
[ 82 121]]

Exercise 4:

Extract all odd numbers from an array of 1-10.

arr = np.arange(10)

odd_arr = arr[arr%2==1]

odd_arr

array([1, 3, 5, 7, 9])

Exercise 5:

Replace all odd numbers in an array of 1-10 with -1.

arr = np.arange(1,10)
arr[arr%2 == 1] = -1
arr

array([-1, 2, -1, 4, -1, 6, -1, 8, -1])

Exercise 6:
Convert a 1D array to a boolean array where all positive values become True.

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

bool_arr = arr > 0

bool_arr
array([ True, False, True, False, True, False])

Exercise 7:
Replace all even numbers in a 1D array with their negative

arr = np.arange(1,20)

arr[arr%2==0] *= -1

arr

array([ 1, -2, 3, -4, 5, -6, 7, -8, 9, -10, 11, -12,


13,
-14, 15, -16, 17, -18, 19])

23N266, pg. 3
Exercise 8:

Create a random 3x3 matrix and normalize it.

matrix = np.random.random((3,3))

print(matrix)

normalized_matrix = (matrix - np.mean(matrix))/np.std(matrix)

print(normalized_matrix)

[[0.26864081 0.84422908 0.33404845]


[0.52243166 0.77305119 0.60968479]
[0.22264608 0.45232604 0.39748489]]
[[-1.09129411 1.7257745 -0.77117324]
[ 0.15081985 1.37741263 0.57785785]
[-1.31640346 -0.19229406 -0.46069995]]

Exercise 9:
Calculate the sum of the diagonal elements of a 3x3 matrix.

arr = np.arange(1,10).reshape(3,3)

print(arr)

diagonal_sum = np.trace(arr)

print(diagonal_sum)

[[1 2 3]
[4 5 6]
[7 8 9]]
15

Exercise 10:

Find the indices of non-zero elements from [1,2,0,0,4,0].

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

non_zero_indices = np.nonzero(arr)

non_zero_indices

(array([0, 1, 4], dtype=int64),)

Exercise 11:

Reverse a 1D array (first element becomes the last).

23N266, pg. 4
arr = np.arange(1,10)

arr = np.flip(arr)

arr

array([9, 8, 7, 6, 5, 4, 3, 2, 1])

Exercise 12:

Create a 3x3 identity matrix

identity = np.eye(3)

identity

array([[1., 0., 0.],


[0., 1., 0.],
[0., 0., 1.]])

Exercise 13:
Reshape a 1D array to a 2D array with 5 rows and 2 columns.

arr = np.arange(10).reshape(5,2)

arr

array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])

Exercise 14:

Stack two arrays vertically.

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

arr2 = np.array([3,4,5,7,4,6])

stacked_array = np.vstack((arr1,arr2))

stacked_array

array([[1, 2, 3, 4, 5, 6],
[3, 4, 5, 7, 4, 6]])

Exercise 15:

23N266, pg. 5
Get the common items between two arrays.

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

arr2 = np.array([3, 4, 5, 6, 7])

common_items = np.intersect1d(arr1, arr2)

print(common_items)

[3 4 5]

Exercise 16:
Create a 5x5 matrix with row values ranging from 0 to 4.

matrix = np.zeros((5,5))

matrix += np.array([0,1,2,3,4])

matrix

array([[0., 1., 2., 3., 4.],


[0., 1., 2., 3., 4.],
[0., 1., 2., 3., 4.],
[0., 1., 2., 3., 4.],
[0., 1., 2., 3., 4.]])

Exercise 17:
Find the index of the maximum value in a 1D array.

arr = np.array([1,2,3,4,5,6,67,8,9])

max_index = np.argmax(arr)

max_index

Exercise 18:

Normalize the values in a 1D array between 0 and 1.

arr = np.array([2, 5, 8, 9, 12, 56])

normalized_arr = (arr - np.min(arr)) / (np.max(arr) - np.min(arr))

print(normalized_arr)

[0. 0.05555556 0.11111111 0.12962963 0.18518519 1. ]

23N266, pg. 6
Exercise 19:

Calculate the dot product of two arrays

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

dot_product = np.dot(arr1, arr2)

print(dot_product)

32

Exercise 20:
Count the number of elements in an array within a specific range.

arr = np.array([1,2,3,4,5,6,45,7,7,5,4,4,5,3,4,4,4,7,7,6,8,9,0])

count_within_range = np.sum((arr>=5) & (arr<=9))

count_within_range

11

Exercise 21:

Find the mean of each row in a 2D array.

arr = np.arange(15).reshape(3,5)

mean = np.mean(arr, axis=1)

mean

array([ 2., 7., 12.])

Exercise 22:

Create a random 4x4 matrix and extract the diagonal elements.

arr = np.arange(16).reshape(4,4)

print(arr)

diagonal_elements = np.diag(arr)

print(diagonal_elements)

23N266, pg. 7
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[ 0 5 10 15]

Exercise 23:

Count the number of occurrences of a specific value in an array.

def countSpecificNum(arr, num):


return np.sum((arr==num))

arr = np.array([1,2,13,4,5,34,6,7,8,5,44,6,45,4,4,3,22,2,2,2])

print(countSpecificNum(arr, 2))

Exercise 24:
Replace all values in a 1D array with the mean of the array.

arr = np.array([1,2,13,4,5,34,6,7,8,5,44,6,45,4,4,3,22,2,2,2])

arr[:] = np.mean(arr)

print(arr)

[10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10]

Exercise 25:

Find the indices of the maximum and minimum values in a 1D array.

arr =
np.array([1,2,4,3,546,45,634,324,2,234,5,3,35,65,6,7,5,34,34,6,36,36,3
6,3,74,86,85])

min = np.argmin(arr)

max = np.argmax(arr)

print(min, max)

0 6

Exercise 26:

Create a 2D array with 1 on the border and 0 inside.

23N266, pg. 8
arr = np.ones((5,5))

arr[1:-1, 1:-1] = 0

arr

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.]])

Exercise 27:

Find the unique values and their counts in a 1D array.

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

unique, counts = np.unique(arr, return_counts=True)

print(unique)

print(counts)

[ 1 2 3 4 5 6 33 53]
[3 4 7 4 3 2 1 1]

Exercise 28:

Create a 3x3 matrix with values ranging from 0 to 8.

arr = np.arange(9).reshape(3,3)

arr

array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])

Exercise 29:
Calculate the exponential of all elements in a 1D array.

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

exponential_arr = np.exp(arr)

print(exponential_arr)

[ 2.71828183 7.3890561 20.08553692 54.59815003 148.4131591 ]

23N266, pg. 9
Exercise 30:

Swap two rows in a 2D array.

arr = np.array(range(15)).reshape(3,5)

arr[[1,2]] = arr[[2,1]]

arr

array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[ 5, 6, 7, 8, 9]])

Exercise 31:

Create a random 3x3 matrix and replace all values greater than 0.5 with 1 and all others with 0.

arr = np.random.random((3,3))

arr[arr > 0.5] = 1

arr[arr <=0.5] = 0

arr

array([[1., 0., 0.],


[0., 0., 0.],
[1., 1., 1.]])

Exercise 32:

Find the indices of the top N maximum values in a 1D array.

arr = np.array([1,2,3,345,4,6,5,4,3,3,5,3,3,42,41,2,5,2])

top_indices = np.argsort(arr)[-5:]

top_indices

array([10, 5, 14, 13, 3], dtype=int64)

Exercise 33:

Calculate the mean of each column in a 2D array.

matrix = np.arange(15).reshape(5,3)

print(matrix)

column_means = np.mean(matrix, axis=0)

23N266, pg. 10
print(column_means)

[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
[6. 7. 8.]

Exercise 34:

Normalize the values in each column of a 2D array.

matrix = np.arange(15).reshape(5,3)

print(matrix)

normalized_matrix = (matrix - np.mean(matrix,


axis=0))/np.std(matrix,axis=0)

print(normalized_matrix)

[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
[[-1.41421356 -1.41421356 -1.41421356]
[-0.70710678 -0.70710678 -0.70710678]
[ 0. 0. 0. ]
[ 0.70710678 0.70710678 0.70710678]
[ 1.41421356 1.41421356 1.41421356]]

Exercise 35:

Concatenate two 1D arrays.

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

concatenated_arr = np.concatenate((arr1, arr2))

print(concatenated_arr)

[1 2 3 4 5 6]

Exercise 36:

Create a 2D array with random values and sort each row.

23N266, pg. 11
arr = np.array([1,2,4,5,43,3,2,4,4,2,2,1,1,1,4,6,7,4]).reshape(2,-1)

print(arr)

sorted_arr = np.sort(arr, axis=1)

print(sorted_arr)

[[ 1 2 4 5 43 3 2 4 4]
[ 2 2 1 1 1 4 6 7 4]]
[[ 1 2 2 3 4 4 4 5 43]
[ 1 1 1 2 2 4 4 6 7]]

Exercise 37:
Compute the mean squared error between two arrays.

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

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

mse = np.mean((arr1-arr2)**2)

print(mse)

1.0

Exercise 38:
Replace all negative values in an array with 0.

arr = np.array([1,2,1,3,2,2,3,-1,-3,-53,43,3,4,3,3,-45,2])

arr[arr<0] = 0

arr

array([ 1, 2, 1, 3, 2, 2, 3, 0, 0, 0, 43, 3, 4, 3, 3, 0,
2])

Exercise 39:
Find the 5th and 95th percentiles of an array.

arr = np.array([1,2,2,4,4,3,4,3,2,4,5,6,6,5,7,8,9,9,7,6,5,5,5])

percentile_5th = np.percentile(arr, 5)

percentile_95th = np.percentile(arr, 95)

print("5th Percentile:", percentile_5th)

23N266, pg. 12
print("95th Percentile:", percentile_95th)

5th Percentile: 2.0


95th Percentile: 8.899999999999999

Exercise 40:

Create a random 2x2 matrix and compute its determinant.

matrix = np.random.random((3,3))

det = np.linalg.det(matrix)

det

-0.04825975536941865

Exercise 41:

Count the number of elements in an array that are greater than the mean.

arr = np.arange(10)

mean = np.mean(arr)

count_above_mean = np.sum(arr > mean)

count_above_mean

Exercise 42:

Calculate the square root of each element in a 1D array.

arr = np.arange(10)

sqrt_arr = np.sqrt(arr)

sqrt_arr

array([0. , 1. , 1.41421356, 1.73205081, 2. ,


2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ])

Exercise 43:

Create a 3x3 matrix and compute the matrix square root.

matrix = np.arange(9).reshape(3,3)

23N266, pg. 13
matrix_sqrt = np.linalg.matrix_power(matrix, 2)

matrix_sqrt

array([[ 15, 18, 21],


[ 42, 54, 66],
[ 69, 90, 111]])

Exercise 44:

Convert the data type of an array to float.

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

float_arr = arr.astype(float)

print(float_arr)

[1. 2. 3. 4.]

Exercise 45:
Calculate the element-wise absolute values of an array.

arr = np.random.random(10)

arr = np.abs(arr)

arr

array([0.95013601, 0.04203099, 0.30889293, 0.67759548, 0.89707516,


0.79961722, 0.60608865, 0.95216799, 0.92700291, 0.78256795])

Exercise 46:

Find the indices where elements of two arrays match.

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

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

intersection = np.where(arr1 == arr2)

intersection

(array([0, 1, 3, 4], dtype=int64),)

Exercise 47:
Calculate the cumulative sum of elements in a 1D array.

23N266, pg. 14
arr = np.array([1, 2, 3, 4, 5])

cumulative_sum = np.cumsum(arr)

print(cumulative_sum)

[ 1 3 6 10 15]

Exercise 48:

Compute the inverse of a 2x2 matrix.

matrix = np.random.random((2, 2))

inverse_matrix = np.linalg.inv(matrix)

print(inverse_matrix)

[[ 1.54082111 -0.37606003]
[-1.64424784 1.56921956]]

Exercise 49:
Count the number of non-zero elements in a 2D array.

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

non_zero_count = np.count_nonzero(matrix)

print(non_zero_count)

Exercise 50:

Create a 2D array and replace all nan values with 0.

matrix = np.array([[1, np.nan, 3], [4, 5, np.nan], [7, 8, 9]])

matrix[np.isnan(matrix)] = 0

print(matrix)

[[1. 0. 3.]
[4. 5. 0.]
[7. 8. 9.]]

Exercise 51:

Find the correlation coefficient between two arrays.

23N266, pg. 15
arr1 = np.array([1, 2, 3, 4, 5])

arr2 = np.array([3, 4, 5, 6, 7])

correlation_coefficient = np.corrcoef(arr1, arr2)[0, 1]

print(correlation_coefficient)

0.9999999999999999

Exercise 52:

Create a 1D array and remove all duplicate values.

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

unique_arr = np.unique(arr)

print(unique_arr)

[1 2 3 4 5]

Exercise 53:

Compute the element-wise product of two arrays.

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

elementwise_product = np.multiply(arr1, arr2)

print(elementwise_product)

[ 4 10 18]

Exercise 54:

Calculate the standard deviation of each column in a 2D array.

matrix = np.random.random((4, 3))

column_stddev = np.std(matrix, axis=0)

print(column_stddev)

[0.31049852 0.14949738 0.15159161]

Exercise 55:

Create a 2D array and set all values above a certain threshold to that threshold.

23N266, pg. 16
matrix = np.random.random((5,5))

threshold = 0.7

matrix[matrix > threshold] = threshold

matrix

array([[0.17831675, 0.7 , 0.7 , 0.12028967, 0.35887835],


[0.55483634, 0.05142095, 0.50811919, 0.65664968, 0.7 ],
[0.18650985, 0.7 , 0.10706599, 0.6939138 , 0.31905637],
[0.7 , 0.32206413, 0.5035072 , 0.34130553, 0.68045198],
[0.23701609, 0.7 , 0.48554565, 0.42624658, 0.32798752]])

Exercise 56:
Create a random 5x5 matrix and replace the maximum value by -1.

matrix = np.random.random((5,5))

max_val_index = np.unravel_index(np.argmax(matrix), matrix.shape)

matrix[max_val_index] = -1

matrix

array([[ 0.48072868, 0.26503263, 0.56328117, 0.22498222,


0.29662355],
[ 0.63383179, 0.77582825, 0.34102343, 0.29991682,
0.40103397],
[ 0.5235903 , 0.58612656, 0.46916179, 0.65325334,
0.39252708],
[ 0.36116028, 0.58172809, 0.73419384, 0.73953475,
0.59317605],
[ 0.02598848, 0.74219128, 0.734576 , -1. ,
0.26986283]])

Exercise 57:
Convert a 1D array of Fahrenheit temperatures to Celsius.

fahrenheit_temps = np.array([32, 68, 100, 212])

celsius_temps = (fahrenheit_temps - 32) * 5/9

print(celsius_temps)

[ 0. 20. 37.77777778 100. ]

Exercise 58:

23N266, pg. 17
Compute the outer product of two arrays.

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

outer_product = np.outer(arr1, arr2)

print(outer_product)

[[ 4 5 6]
[ 8 10 12]
[12 15 18]]

Exercise 59:

Create a 1D array with 10 equidistant values between 0 and 1.

equidistant_arr = np.linspace(0, 1, 10)

print(equidistant_arr)

[0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556


0.66666667 0.77777778 0.88888889 1. ]

Exercise 60:
Compute the cross product of two 3D arrays.

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

cross_product = np.cross(arr1, arr2)

print(cross_product)

[-3 6 -3]

Exercise 61:

Calculate the percentile along a specific axis of a 2D array.

matrix = np.random.random((3, 4))

percentiles_axis1 = np.percentile(matrix, 75, axis=1)

print(percentiles_axis1)

[0.61651231 0.93810749 0.75882447]

23N266, pg. 18
Exercise 62:

Create a 1D array and add a border of 0s around it.

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

arr_with_border = np.pad(arr, (1, 1), mode='constant',


constant_values=0)

print(arr_with_border)

[0 1 2 3 4 0]

Exercise 63:

Compute the histogram of a 1D array.

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

hist, bins = np.histogram(arr, bins=[1, 2, 3, 4])

print("Histogram:", hist)

print("Bin edges:", bins)

Histogram: [2 3 4]
Bin edges: [1 2 3 4]

Exercise 64:

Create a 2D array with random values and normalize each row.

matrix = np.random.random((4, 3))

normalized_rows = matrix / np.linalg.norm(matrix, axis=1,


keepdims=True)

print(normalized_rows)

[[0.75532646 0.65356277 0.04834915]


[0.17395684 0.82918385 0.53121856]
[0.3212521 0.94229398 0.09422915]
[0.76964872 0.6381653 0.01964428]]

Exercise 65:

Create a random 2D array and sort it by the second column.

matrix = np.random.random((3, 4))

sorted_matrix_by_column2 = matrix[matrix[:, 1].argsort()]

23N266, pg. 19
print(sorted_matrix_by_column2)

[[0.92426874 0.06340264 0.3873512 0.12088286]


[0.43923843 0.61210146 0.49905163 0.50426075]
[0.72573401 0.81238846 0.10335873 0.32350213]]

Exercise 66:
Calculate the determinant of a 3x3 matrix.

matrix = np.random.random((3, 3))

determinant = np.linalg.det(matrix)

print(determinant)

0.029061429535904963

Exercise 67:
Calculate the element-wise exponentiation of a 1D array.

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

exponentiated_arr = np.exp(arr)

print(exponentiated_arr)

[ 7.3890561 20.08553692 54.59815003]

Exercise 68:

Calculate the Frobenius norm of a 2D array.

matrix = np.random.random((3, 4))

frobenius_norm = np.linalg.norm(matrix)

print(frobenius_norm)

2.219522924106627

Exercise 69:

Create a 2D array with random values and replace the maximum value with the minimum.

matrix = np.random.random((3, 4))

max_value_index = np.unravel_index(np.argmax(matrix), matrix.shape)

23N266, pg. 20
min_value = np.min(matrix)

matrix[max_value_index] = min_value

print(matrix)

[[0.72467241 0.56733823 0.3393165 0.01228913]


[0.20210265 0.94593019 0.72487236 0.30967189]
[0.91276323 0.61018446 0.40409198 0.01228913]]

Exercise 70:

Compute the matrix multiplication of two 2D arrays.

matrix1 = np.random.random((3, 4))

matrix2 = np.random.random((4, 5))

matrix_multiplication = np.dot(matrix1, matrix2)

print(matrix_multiplication)

[[0.77478069 0.60523536 1.05563108 0.45269143 2.04129084]


[0.54752109 0.45162638 0.77544268 0.33315081 1.50437288]
[0.70614313 0.64663806 1.04747359 0.41734386 1.64753123]]

Exercise 71:
Create a 1D array and set the values between 10 and 20 to 0.

arr = np.array([5, 15, 12, 18, 25])

arr[(arr >= 10) & (arr <= 20)] = 0

print(arr)

[ 5 0 0 0 25]

Exercise 72:

Compute the inverse hyperbolic sine of each element in a 1D array.

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

inverse_sineh_arr = np.arcsinh(arr)

print(inverse_sineh_arr)

[0.88137359 1.44363548 1.81844646 2.09471255]

Exercise 73:

23N266, pg. 21
Compute the Kronecker product of two arrays.

arr1 = np.array([1, 2])

arr2 = np.array([3, 4])

kronecker_product = np.kron(arr1, arr2)

print(kronecker_product)

[3 4 6 8]

Exercise 74:
Calculate the mean absolute deviation of a 1D array.

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

mean_absolute_deviation = np.mean(np.abs(arr - np.mean(arr)))

print(mean_absolute_deviation)

1.2

Exercise 75:
Create a 3x3 matrix and set all values above the main diagonal to zero.

matrix = np.random.random((3, 3))

matrix[np.triu_indices(3, 1)] = 0

print(matrix)

[[0.03592082 0. 0. ]
[0.98343727 0.55001654 0. ]
[0.83016671 0.31007078 0.81221473]]

Exercise 76:

Count the number of occurrences of each unique value in a 1D array.

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

unique_values, counts = np.unique(arr, return_counts=True)

print("Unique values:", unique_values)

print("Counts:", counts)

23N266, pg. 22
Unique values: [1 2 3 4]
Counts: [1 2 3 1]

Exercise 77:

Compute the cumulative product of elements along a given axis in a 2D array.

matrix = np.random.random((3, 4))

cumulative_product_axis0 = np.cumprod(matrix, axis=0)

print(cumulative_product_axis0)

[[0.62431053 0.57143098 0.37692476 0.68132931]


[0.43303688 0.3129361 0.05512402 0.06588338]
[0.00943823 0.14936036 0.00399478 0.02933527]]

Exercise 78:
Round elements of a 1D array to the nearest integer.

arr = np.array([1.2, 2.7, 3.5, 4.9])

rounded_arr = np.round(arr)

print(rounded_arr)

[1. 3. 4. 5.]

Exercise 79:

Create a 1D array and append a new element to the end.

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

new_element = 4

arr = np.append(arr, new_element)

print(arr)

[1 2 3 4]

Exercise 80:

Calculate the element-wise absolute difference between two arrays.

arr1 = np.array([3, 7, 1, 10, 4])

arr2 = np.array([2, 5, 8, 1, 7])

23N266, pg. 23
absolute_difference = np.abs(arr1 - arr2)

print(absolute_difference)

[1 2 7 9 3]

Exercise 81:

Create a 2D array with random values and replace the maximum value in each row with -1.

matrix = np.random.random((3, 4))

max_values_indices = np.argmax(matrix, axis=1)

matrix[np.arange(matrix.shape[0]), max_values_indices] = -1

print(matrix)
[[ 0.02028369 -1. 0.42466127 0.94363836]
[ 0.07116187 -1. 0.08768886 0.52489983]
[-1. 0.4391846 0.35890509 0.12949558]]

Exercise 82:

Normalize the columns of a 2D array to have a sum of 1.

matrix = np.random.random((3, 4))

normalized_columns = matrix / np.sum(matrix, axis=0, keepdims=True)

print(normalized_columns)

[[0.11148859 0.56064107 0.04281364 0.40028399]


[0.51577854 0.28485268 0.85776505 0.21456393]
[0.37273287 0.15450625 0.09942132 0.38515207]]

Exercise 83:
Find the indices of the top N minimum values in a 1D array.

arr = np.array([10, 5, 8, 1, 7])

top_indices = np.argsort(arr)[:2]

print(top_indices)

[3 1]

Exercise 84:

23N266, pg. 24
Convert the elements of a 1D array to strings.

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

string_arr = arr.astype(str)

print(string_arr)

['1' '2' '3' '4']

Exercise 85:

Compute the percentile rank of each element in a 1D array.

from scipy.stats import percentileofscore

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

# Calculate percentile rank for each element in arr

percentile_rank = np.array([percentileofscore(arr, value) for value in


arr])

print(percentile_rank)

[ 20. 40. 60. 80. 100.]

Exercise 86:
Create a 1D array and shuffle its elements randomly.

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

np.random.shuffle(arr)

print(arr)

[4 1 3 2 5]

Exercise 87:

Check if all elements in a 1D array are non-zero.

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

all_nonzero = np.all(arr != 0)

print(all_nonzero)

True

23N266, pg. 25
Exercise 88:

Find the indices of the maximum value in each row of a 2D array.

matrix = np.random.random((3, 4))

max_indices_per_row = np.argmax(matrix, axis=1)

print(max_indices_per_row)

[0 1 1]

Exercise 89:
Create a 2D array and replace all nan values with the mean of the array.

matrix = np.array([[1, np.nan, 3], [4, 5, np.nan], [7, 8, 9]])

nan_mean = np.nanmean(matrix)

matrix[np.isnan(matrix)] = nan_mean

print(matrix)

[[1. 5.28571429 3. ]
[4. 5. 5.28571429]
[7. 8. 9. ]]

Exercise 90:

Calculate the mean of each row in a 2D array ignoring nan values.

matrix = np.array([[1, 2, np.nan], [4, np.nan, 6], [7, 8, 9]])

row_means_ignore_nan = np.nanmean(matrix, axis=1)

print(row_means_ignore_nan)

[1.5 5. 8. ]

Exercise 91:
Compute the sum of diagonal elements in a 2D array.

matrix = np.random.random((3, 3))

diagonal_sum = np.trace(matrix)

print(diagonal_sum)

2.1246107289884653

23N266, pg. 26
Exercise 92:

Convert radians to degrees for each element in a 1D array.

arr_in_radians = np.array([np.pi/2, np.pi, 3*np.pi/2])

arr_in_degrees = np.degrees(arr_in_radians)

print(arr_in_degrees)

[ 90. 180. 270.]

Exercise 93:
Calculate the pairwise Euclidean distance between two arrays.

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

euclidean_distance = np.linalg.norm(arr1 - arr2)

print(euclidean_distance)

5.196152422706632

Exercise 94:

Create a 1D array and set the values between the 25th and 75th percentile to 0.

arr = np.array([10, 20, 30, 40, 50])

percentile_25th = np.percentile(arr, 25)

percentile_75th = np.percentile(arr, 75)

arr[(arr >= percentile_25th) & (arr <= percentile_75th)] = 0

print(arr)

[10 0 0 0 50]

Exercise 95:

Calculate the element-wise square of the difference between two arrays.

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

squared_difference = (arr1 - arr2)**2

23N266, pg. 27
print(squared_difference)

[9 9 9]

Exercise 96:

Replace all even numbers in a 1D array with the next odd number.

arr = np.array([2, 5, 8, 12, 15])

arr[arr % 2 == 0] += 1

print(arr)

[ 3 5 9 13 15]

Exercise 97:

Create a 2D array and normalize each column by its range..

matrix = np.random.random((3, 4))

normalized_columns_range = (matrix - np.min(matrix, axis=0)) /


(np.max(matrix, axis=0) - np.min(matrix, axis=0))

print(normalized_columns_range)

[[1. 0. 0.72054908 0. ]
[0. 1. 0. 1. ]
[0.57570135 0.07701889 1. 0.43791495]]

Exercise 98:

Compute the cumulative sum of elements along a given axis in a 2D array.

matrix = np.random.random((3, 4))

cumulative_sum_axis1 = np.cumsum(matrix, axis=1)

print(cumulative_sum_axis1)

[[0.66617151 1.21690075 1.73102363 2.38773452]


[0.37125332 1.11307989 1.84774178 1.98231611]
[0.05101378 0.95518553 1.65657704 2.48889002]]

Exercise 99:

Check if any element in a 1D array is non-zero.

23N266, pg. 28
arr = np.array([0, 0, 0, 1, 0])

any_nonzero = np.any(arr != 0)

print(any_nonzero)

True

Exercise 100:

Create a 2D array with random integers and replace all values greater than a certain threshold
with that threshold.

matrix = np.random.randint(0, 100, size=(3, 4))

threshold = 75

matrix[matrix > threshold] = threshold

print(matrix)

[[75 13 12 66]
[62 62 0 63]
[52 75 40 75]]

23N266, pg. 29

You might also like