Part-II-B Basic NumPy Tutorials-II
March 1, 2025
1 Python : Numpy Tutorial
1.1 Introduction
Welcome to this NumPy tutorial!
NumPy (Numerical Python) is an essential Python library for numerical computations. This tuto-
rial is designed specifically for medical researchers with no programming background. By the end
of this tutorial, you will have a solid foundation in NumPy and be able to use it for your scientific
research, including data analysis in the your domain.
1.1.1 Why Learn NumPy?
1. Efficient Data Handling: Perform fast mathematical operations on large datasets.
2. Research Applications: Useful for manipulating and analyzing research data, such as
patient records, clinical trials, and imaging data.
3. Integration: Works seamlessly with other Python libraries like Pandas, Matplotlib, and
SciPy.
1.1.2 Key Concepts Covered
In this tutorial, we will cover: 1. Basics of NumPy: Arrays, their creation, and manipulation. 2.
Array operations: Mathematical, statistical, and logical. 3. Reshaping, indexing, and slicing arrays.
4. Working with real-world medical data examples. 5. Saving and loading data for reproducible
research. 6. Interactive quiz to reinforce learning.
1
2 NumPy Functionality Table
Below is a comprehensive list of NumPy functions, their descriptions, and examples:
Function/Method
Description Example Output
[Link]() Creates an array from a list or [Link]([1, 2, 3]) [1, 2, 3]
tuple.
[Link]() Creates an array of all zeros with a [Link]((2, 2)) [[0., 0.], [0.,
specified shape. 0.]]
[Link]() Creates an array of all ones with a [Link]((2, 3)) [[1., 1., 1.],
specified shape. [1., 1., 1.]]
[Link]() Creates an array with evenly [Link](0, 10, 2) [0, 2, 4, 6, 8]
spaced values within a range.
[Link]() Creates an array with evenly [Link](0, 1, [0., 0.25, 0.5,
spaced values over a range. 5) 0.75, 1.]
[Link]() Reshapes an array to a new shape. [Link]([1, 2, 3, [[1, 2], [3,
4]).reshape(2, 2) 4]]
[Link]() Calculates the mean of array [Link]([1, 2, 3, 2.5
elements. 4])
[Link]() Calculates the median of array [Link]([1, 2, 3, 2.5
elements. 4])
[Link]() Calculates the standard deviation. [Link]([1, 2, 3, 1.118
4])
[Link]() Sums array elements. [Link]([1, 2, 3, 10
4])
[Link]() Finds the maximum value in an [Link]([1, 2, 3, 4
array. 4])
[Link]() Finds the minimum value in an [Link]([1, 2, 3, 1
array. 4])
[Link]() Sorts an array. [Link]([3, 1, 2]) [1, 2, 3]
[Link]() Finds unique elements in an array. [Link]([1, 2, 2, [1, 2, 3]
3])
Generates random numbers
[Link]() [Link](2, Random 2x2
between 0 and 1. 2) array
Generates random integers within
[Link]() [Link](0, Random integers
a range. 10, (2, 2)) 2x2 array
Solves a linear equation system.
[Link]() [Link]([[2, Solution array
3], [3, 2]], [8,
7])
[Link]() Saves an array to a binary file. [Link]('[Link]', Saves to file
arr)
[Link]() Loads an array from a binary file. [Link]('[Link]') Loaded array
2
3 Topics to be Covered in This Tutorial
In the table above, we will explore a few commonly used functions as a starting point to avoid
complexity. Later on, you can try them all on your own.
1. [Link]()
2. [Link]()
3. [Link]()
4. [Link]()
5. [Link]()
6. [Link]()
7. [Link]()
8. [Link]()
9. [Link]()
10. [Link]()
11. [Link]()
12. [Link]()
13. [Link]()
14. [Link]()
15. [Link]()
16. [Link]()
17. [Link]()
3.1 We will use simple examples to demonstrate how some of these function
works…
4 Function Explanations and Examples
[ ]:
[12]: import numpy as np
4.0.1 1. Creating Arrays with [Link]()
The [Link]() function is used to create an array from a list or tuple. Arrays are the building
blocks of NumPy.
[13]: # Example: Creating a 1D array
array = [Link]([1, 2, 3, 4])
print("Array:", array)
Array: [1 2 3 4]
3
Explanation: - [Link]([1, 2, 3, 4]): Converts the list [1, 2, 3, 4] into a NumPy array.
- Output: [1, 2, 3, 4]
4.0.2 2. Creating an Array of Zeros with [Link]()
This function creates an array filled with zeros of a specified shape.
[14]: # Example: Creating a 2x3 array of zeros
zeros_array = [Link]((2, 3))
print("Zeros Array:\n", zeros_array)
Zeros Array:
[[0. 0. 0.]
[0. 0. 0.]]
Explanation: - [Link]((2, 3)): Creates a 2x3 array filled with zeros. - Output: [[0., 0.,
0.], [0., 0., 0.]]
4.0.3 3. Creating an Array of Ones with [Link]()
This function creates an array filled with ones of a specified shape.
[15]: # Example: Creating a 3x2 array of ones
ones_array = [Link]((3, 2))
print("Ones Array:\n", ones_array)
Ones Array:
[[1. 1.]
[1. 1.]
[1. 1.]]
Explanation: - [Link]((3, 2)): Creates a 3x2 array filled with ones. - Output: [[1., 1.],
[1., 1.], [1., 1.]]
4.0.4 4. Generating an Array with a Range of Values Using [Link]()
The [Link]() function creates an array with evenly spaced values within a given range.
[16]: # Example: Generating an array from 0 to 9 with a step of 2
range_array = [Link](0, 10, 2)
print("Range Array:", range_array)
Range Array: [0 2 4 6 8]
Explanation: - [Link](0, 10, 2): Generates values from 0 to 9 with a step of 2. - Output:
[0, 2, 4, 6, 8]
4
4.0.5 5. Generating Evenly Spaced Values Using [Link]()
The [Link]() function generates evenly spaced numbers over a specified interval.
[17]: # Example: Generating 5 evenly spaced values between 0 and 1
linspace_array = [Link](0, 1, 5)
print("Linspace Array:", linspace_array)
Linspace Array: [0. 0.25 0.5 0.75 1. ]
Explanation: - [Link](0, 1, 5): Generates 5 evenly spaced values between 0 and 1. -
Output: [0., 0.25, 0.5, 0.75, 1.]
4.0.6 6. Reshaping Arrays with [Link]()
The [Link]() function reshapes an array to a specified shape.
[18]: # Example: Reshaping a 1D array to 2x2
original_array = [Link]([1, 2, 3, 4])
reshaped_array = original_array.reshape(2, 2)
print("Original Array:", original_array)
print("Reshaped Array:\n", reshaped_array)
Original Array: [1 2 3 4]
Reshaped Array:
[[1 2]
[3 4]]
Explanation: - original_array.reshape(2, 2): Converts the 1D array [1, 2, 3, 4] to a 2x2
array. - Output: [[1, 2], [3, 4]]
4.0.7 7. Calculating the Mean with [Link]()
The [Link]() function calculates the mean of array elements
[19]: # Calculating the mean of an array
data = [Link]([1, 2, 3, 4, 5])
mean_value = [Link](data)
print('Mean Value:', mean_value)
Mean Value: 3.0
Explanation: - [Link]([1, 2, 3, 4, 5]): Calculates the mean of the array elements. - Out-
put: 3.0
5
4.0.8 8. Calculating the Median with [Link]()
The [Link]() function calculates the median of the array elements. The median is the middle
value when the data is sorted.
[20]: # Example: Calculating the median of an array
array = [Link]([1, 2, 3, 4, 5])
median_value = [Link](array)
print("Median:", median_value)
Median: 3.0
Explanation: - [Link]([1, 2, 3, 4, 5]): Calculates the median of the array elements. -
Output: 3.0
4.0.9 9. Calculating the Standard Deviation with [Link]()
The [Link]() function calculates the standard deviation of the array elements, which measures
the spread or dispersion of the data.
[21]: # Example: Calculating the standard deviation of an array
array = [Link]([1, 2, 3, 4, 5])
std_dev = [Link](array)
print("Standard Deviation:", std_dev)
Standard Deviation: 1.4142135623730951
Explanation: - [Link]([1, 2, 3, 4, 5]): Calculates the standard deviation of the array ele-
ments. - Output: 1.4142135623730951
4.0.10 10. Summing the Elements with [Link]()
The [Link]() function calculates the sum of all elements in the array.
[22]: # Example: Summing the elements of an array
array = [Link]([1, 2, 3, 4, 5])
sum_value = [Link](array)
print("Sum:", sum_value)
Sum: 15
Explanation: - [Link]([1, 2, 3, 4, 5]): Sums the array elements. - Output: 15
6
4.0.11 11. Finding the Maximum Value with [Link]()
The [Link]() function returns the maximum value from the array.
[23]: # Example: Finding the maximum value in an array
array = [Link]([1, 2, 3, 4, 5])
max_value = [Link](array)
print("Max:", max_value)
Max: 5
Explanation: - [Link]([1, 2, 3, 4, 5]): Finds the maximum value in the array. - Output: 5
4.0.12 12. Finding the Minimum Value with [Link]()
The [Link]() function returns the minimum value from the array.
[24]: # Example: Finding the minimum value in an array
array = [Link]([1, 2, 3, 4, 5])
min_value = [Link](array)
print("Min:", min_value)
Min: 1
Explanation: - [Link]([1, 2, 3, 4, 5]): Finds the minimum value in the array. - Output: 1
4.0.13 13. Sorting the Array with [Link]()
The [Link]() function sorts the elements of the array in ascending order.
[25]: # Example: Sorting an array
array = [Link]([5, 3, 1, 4, 2])
sorted_array = [Link](array)
print("Sorted Array:", sorted_array)
Sorted Array: [1 2 3 4 5]
Explanation: - [Link]([5, 3, 1, 4, 2]): Sorts the array in ascending order. - Output: [1,
2, 3, 4, 5]
4.0.14 14. Generating Random Numbers with [Link]()
The [Link]() function generates random numbers from a uniform distribution between
0 and 1.
7
[26]: # Example: Generating a 2x2 array of random numbers
random_array = [Link](2, 2)
print("Random Array:\n", random_array)
Random Array:
[[0.64611576 0.14854119]
[0.03401987 0.05335882]]
Explanation: - [Link](2, 2): Generates a 2x2 array with random values between 0
and 1. - Output: A 2x2 array with random values.
4.0.15 15. Solving Linear Systems with [Link]()
The [Link]() function solves a system of linear equations of the form Ax = B.
[27]: # Example: Solving a system of equations Ax = B
A = [Link]([[3, 1], [1, 2]])
B = [Link]([9, 8])
solution = [Link](A, B)
print("Solution:", solution)
Solution: [2. 3.]
Explanation: - [Link](A, B): Solves the system of linear equations A * x = B. -
Output: The solution for x.
4.0.16 16. Saving Arrays to a File with [Link]()
The [Link]() function saves an array to a binary file in .npy format.
[28]: # Example: Saving an array to a file
array = [Link]([1, 2, 3, 4, 5])
[Link]('[Link]', array)
print("Array saved to '[Link]'")
Array saved to '[Link]'
Explanation: - [Link]('[Link]', array): Saves the array to the file named ‘[Link]’. -
Output: A file is saved in the current directory.
4.0.17 17. Loading Arrays from a File with [Link]()
The [Link]() function loads an array from a file saved in .npy format.
8
[29]: # Example: Loading an array from a file
loaded_array = [Link]('[Link]')
print("Loaded Array:", loaded_array)
Loaded Array: [1 2 3 4 5]
Explanation: - [Link]('[Link]'): Loads the array from the file ‘[Link]’. - Output: The
loaded array from the file. “‘
4.1 Quiz
4.1.1 Test Your Knowledge
1. What function is used to create an array filled with zeros?
• A) [Link]()
• B) [Link]()
• C) [Link]()
2. How do you reshape a 1D array into a 2D array?
• A) [Link]()
• B) [Link]()
• C) [Link]()
[ ]:
9
Main
March 1, 2025
1 Handling Images with NumPy
[25]: import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
1. Open an image file
2. Read the image file into a numpy array
[26]: png_img = [Link]('standard_test_images/[Link]', -1)
# png_img = [Link]('[Link]', -1)
## -1 flag is used to read the image as it is, without any changes
png_img.shape
[26]: (512, 512, 4)
[27]: # convert the image to RGB (OpenCV uses BGR)
png_img_rgb = [Link](png_img, cv.COLOR_BGR2RGB)
print(png_img_rgb.shape)
# plot image inline with matplotlib
[Link](png_img_rgb)
# [Link]('off')
[Link]()
(512, 512, 3)
1
3. Filter np array to extract red | green | blue colors from the image and repaint image with
only red component and display it
[28]: # Ensure the image has 3 channels (RGB), ignoring alpha if present
if png_img_rgb.shape[-1] == 4: # RGBA
png_img_rgb = png_img_rgb[:, :, :3]
# create a placeholder image to store the image with only 0 values
zero_channel = np.zeros_like(png_img[:,:,0])
# split the image into its 3 channels
red_channel = png_img[:,:,0]
red_img = [Link]((red_channel, zero_channel, zero_channel))
green_channel = png_img[:,:,1]
green_img = [Link]((zero_channel, green_channel, zero_channel))
blue_channel = png_img[:,:,0]
blue_img = [Link]((zero_channel, zero_channel, blue_channel))
# plot the 3 images in a subplot
[Link](figsize=(10,3))
2
[Link]('off')
[Link](131)
[Link](red_img, cmap='gray')
[Link]('Red channel')
[Link]('off')
[Link](132)
[Link](green_img, cmap='gray')
[Link]('Green channel')
[Link]('off')
[Link](133)
[Link](blue_img, cmap='gray')
[Link]('Blue channel')
[Link]('off')
# [Link]('off')
[Link]()
Convert the image to grayscale and display it
[29]: # using existing libaray function and calculate time taken
import time
start = [Link]()
gray_img = [Link](png_img, cv.COLOR_BGR2GRAY)
print(gray_img.shape)
end = [Link]()
diff_lib = end - start
print(f'Time taken by OpenCV function: {diff_lib} seconds')
# the formula to compute average used here is 0.299*R + 0.587*G + 0.114*B
# because the human eye is more sensitive to green color, so it is given more␣
↪weight
3
[Link](gray_img, cmap='gray')
[Link]('off')
[Link]()
(512, 512)
Time taken by OpenCV function: 0.0003559589385986328 seconds
[30]: start = [Link]()
# using for loop
gray_img = [Link]((png_img.shape[0], png_img.shape[1]))
for i in range(png_img.shape[0]):
for j in range(png_img.shape[1]):
gray_img[i,j] = (png_img[i,j,0]//3 + png_img[i,j,1]//3 + png_img[i,j,2]/
↪/3)
end = [Link]()
diff_for = end - start
print(f'Time taken by for loop: {diff_for} seconds')
[Link](gray_img, cmap='gray')
[Link]('off')
[Link]()
# time differece
speedup = diff_for/diff_lib
4
print(f'Speedup by using numpy is: {speedup:.2f}x')
Time taken by for loop: 0.3691413402557373 seconds
Speedup by using numpy is: 1037.03x
5. draw a histogram of the grayscale image
[31]: [Link](figsize=(10,3))
[Link](121)
[Link]('Grayscale Image')
[Link](gray_img,cmap='gray')
[Link]('off')
# [Link]()
[Link](122)
[Link]('Histogram')
[Link](gray_img.ravel(), bins=256, range=(0.0, 255.0), fc='k', ec='k')
[Link]()
5
6. Let X be the np matrix of the grayscale image
• obtain Y = X.T (transpose of X)
• obtain Z = Y.X (matrix multiplication of Y and X)
[32]: X = gray_img
print(f"{[Link]=}")
Y = X.T
print(f"{[Link]=}")
# multiply Y and X
Z = [Link](Y,X)
print(f"{[Link]=}")
[Link]=(512, 512)
[Link]=(512, 512)
[Link]=(512, 512)
7. Obtain a portion of the grayscale image and save it in an array A
[33]: P = int([Link][0]*.4),int([Link][1]*.4)
Q = int([Link][0]*.7),int([Link][1]*.7)
print(f"{P=}")
print(f"{Q=}")
# crop the image
A = gray_img[P[0]:Q[0], P[1]:Q[1]]
P=(204, 204)
Q=(358, 358)
8. Display the partimage A
6
[39]: # display the originall and cropped image
[Link](figsize=(7,4))
[Link](121)
[Link]('Original Image')
[Link](gray_img, cmap='gray')
# display P and Q on the image
[Link]([P[1], Q[1], Q[1], P[1], P[1]], [P[0], P[0], Q[0], Q[0], P[0]], 'r')
[Link](P[1], P[0], 'P', color='b', fontsize=16)
[Link](Q[1], Q[0], 'Q', color='b', fontsize=16)
[Link]('off')
[Link](122)
[Link]('Cropped Image A[P:Q]')
[Link](A, cmap='gray')
[Link]('off')
[Link]()