NumPy
NumPy stands for Numerical Python, it’s a Python module that was created in 2005 for working with arrays,
Install (If pip does not work, try pip3)
pip # Python’s package manager used to install libraries
install # Tells pip to download and install a package
numpy # A Python library for numerical and scientific computing
(Host) $ pip install numpy
import numpy as np # Imports the NumPy library and gives it the alias np
import numpy as np
Create an Array
A data structure that stores more than one item of the same type; it’s similar to lists in Python but more efficient, convenient, requires less memory and fast. To create an array, use the .array() with the items surrounded by [], you can also pass the dtype parameter to the .array() method for describing the data type
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([1,2,3]) # Creates a NumPy array from the Python list
print(arr) # Prints the array
import numpy as np
arr = np.array([1,2,3])
print(arr)
Result
[1 2 3]
Data Types
If you want to describe the data type, pass dtype the with the first letter of the data type, you can also get the type size using np.dtype('b').itemsize
i integer
b boolean
u unsigned integer
f float
c complex float
m timedelta
M datetime
O object
S string
U unicode string
V void
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([1,2,3], dtype=’f’) # Creates a NumPy array from the Python list and set the data type of the elements to float32, so the numbers are stored as floating-point numbers
print(arr) # Prints the array
import numpy as np
arr = np.array([1,2,3], dtype='f')
print(arr)
Result
[1. 2. 3.]
Create Multi-Dimensional
To create a multi-dimensional array, use the .array() with the items surrounded by [] within [], you can also pass the dtype parameter to the .array() method for describing the data type
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([[‘item 1′,’item 2’],[‘item 1′,’item 2’]]) # Creates a 2-dimensional NumPy array (a 2×2 “matrix”) from a nested list
print(arr) # Prints the array
import numpy as np
arr = np.array([['item 1','item 2'],['item 1','item 2']])
print(arr)
Result
[['item 1' 'item 2']
['item 1' 'item 2']]
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([[1,2],[1,2]], dtype=’f’) # Creates a 2-dimensional NumPy array (a 2×2 “matrix”) from a nested list and set the data type of the elements to float32, so the numbers are stored as floating-point numbers
print(arr) # Prints the array
import numpy as np
arr = np.array([[1,2],[1,2]], dtype='f')
print(arr)
Result
[[1. 2.]
[1. 2.]]
Create Empty Arrays
To create an empty array, you can either use the .empty() or .zeros() methods. The .empty() method will return an array without initializing entries, whereas the .zeros() method will return an array filled with zeros,.
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.zeros(shape=(10),dtype=’i’) # Creates a 10×1 array, all items initialized to 0s, stored as integer numbers
print(arr) # Prints the array
import numpy as np
arr = np.zeros(shape=(10),dtype='i')
print(arr)
Result
[0 0 0 0 0 0 0 0 0 0]
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.empty(shape=(10)) # Creates a 10×1 array, do not initialize the items, stored as integer numbers
print(arr) # Prints the array
import numpy as np
arr = np.empty(shape=(10),dtype='i')
print(arr)
Result
[ 0 1072693248 0 1074135040 0 1075314688
0 1076199424 0 1076953088]
Create an Array Filled With Ones
To create an array that has 1s in it, you can either use the .ones() method
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.ones(shape=(10),dtype=’i’) # Creates a 10×1 array, do not initialize the items, stored as integer numbers
print(arr) # Prints the array
import numpy as np
arr = np.ones(shape=(10),dtype='i')
print(arr)
Result
[1 1 1 1 1 1 1 1 1 1]
Accessing Elements
To access an element of an array, use the index. E.g., to access the first item in a 1d array, you can do [0]. To access 2nd element of the second array in a 2d array, you can do [1][1], and so on
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([1,2], dtype=’f’) # Creates an array with values 1 and 2, set the data type of the elements to float32.
print(arr[0]) # Prints the first element of the array (indexing starts at 0).
import numpy as np
arr = np.array([1,2], dtype='f')
print(arr[0])
Result
1.0
Slicing Arrays
To slice an array, use the smart indexing [], you can do something like this [start:end] or [start:end:step]
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([1,2,3,4,5]) # Creates an array with values 1,2,3,4,5
print(arr[1:4]) # The syntax is arr[start:stop], which selects elements starting from index start up to but not including index stop, prints the selected items
import numpy as np
arr = np.array([1,2,3,4,5])
print(arr[1:4])
Result
[2 3 4]
Get Array Size
To get number of items of an array, use the .size() method
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([[1,2],[1,2]], dtype=’f’) # Creates a 2-dimensional NumPy array (a 2×2 “matrix”) from a nested list, and set the data type of the elements to float32
print(arr.size) # Prints the array size (The total of items in the array)
Example
import numpy as np
arr = np.array([[1,2],[1,2]], dtype='f')
print(arr.size)
Result
4
Get Array Shape
To get the shape of an array, use the .shape() method
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([[1,2],[1,2]], dtype=’f’) # Creates a 2-dimensional NumPy array (a 2×2 “matrix”) from a nested list, and set the data type of the elements to float32
print(arr.shape) # Prints the array size (The total of items in the array)
Example
import numpy as np
arr = np.array([[1,2],[1,2]], dtype='f')
print(arr.shape)
Result
(2, 2)
Reshape Arrays
You can reshape an array using the .reshape() method
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([1,2,3,4,5,6]) # Creates an array with values 1,2,3,4,5,6
arr = arr.reshape(2,3) # Reshapes the array to 2×3 (2 rows and 3 columns)
print(arr) # Prints the array
import numpy as np
arr = np.array([1,2,3,4,5,6])
arr = arr.reshape(2,3)
print(arr)
Result
[[1 2 3]
[4 5 6]]
Flatten Arrays
You can flatten (Convert from multi-dimensional to one-dimensional) an array using the .reshape() method with -1
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([[1,2,3],[4,5,6]]) # Creates a 2d array
arr = arr.reshape(2,3) # Reshapes the array to a 1d array
print(arr) # Prints the array
import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
arr = arr.reshape(-1)
print(arr)
Result
[1 2 3 4 5 6]
Finding Elements
To find an element, use the np.argwhere() method
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([[1,2,3],[4,5,6]]) # Creates a 2d array
print(np.argwhere(arr == 33)) # Prints the row and column location(s) where the value 33 appears in the array
import numpy as np
arr = np.array([[1,2,3],[11,22,33]])
print(np.argwhere(arr == 33))
Result
[[1 2]]
Removing Elements
To remove an element, use the np.delete() method
Example
import numpy as np # Imports the NumPy library and gives it the alias np
arr = np.array([1,2,3,4,5,6]) # Creates an array with values 1,2,3,4,5,6,7,8
index = np.argwhere(arr == 4) # Finds the row and column location(s) where the value 4 appears in the array
arr = np.delete(arr, index) # Removes the element(s) at the given index from arr, then stores the result back in arr
print(arr) # Prints the array
import numpy as np
arr = np.array([1,2,3,4,5,6,7,8])
index = np.argwhere(arr == 4)
arr = np.delete(arr, index)
print(arr)
Result
[1 2 3 5 6 7 8]
# Add arr = arr[arr != 4]
#np.place(arr,(arr == 4),5)
Creating Images
The following represents a single pixel with RGB values of (0, 0, 0), which is black.
Example
import numpy as np # Imports the NumPy library and gives it the alias np
import matplotlib.pyplot as plt # Import Matplotlib for plotting and image display
pixel_rgb = np.array([[[0, 0, 0]]], dtype=np.uint8) # Create a 1×1 image with an RGB pixel value of (0, 0, 0) – This represents a single black pixel, dtype=np.uint8 ensures values are in the valid range for image data (0–255)
plt.imshow(pixel_rgb) # Display the RGB pixel as an image
plt.title(“Example”) # Add a title above the image
plt.axis(‘off’) # Remove x and y axis ticks for a cleaner image display
plt.show() # Render the image on the screen
import numpy as np
import matplotlib.pyplot as plt
pixel_rgb = np.array([[[0, 0, 0]]], dtype=np.uint8)
plt.imshow(pixel_rgb)
plt.title("Example")
plt.axis('off')
plt.show()
Example
import numpy as np # Import NumPy for array creation and manipulation
from PIL import Image # Import Image module (not used directly here)
import matplotlib.pyplot as plt # Import matplotlib for image display (not used here)
img = np.zeros([1,1,3], dtype=np.uint8) # Create a 1×1 RGB image array initialized to zeros
img.fill(0) # Fill the array with 0 (black pixel)
print(img) # Print the pixel values of the image array
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
img = np.zeros([1,1,3],dtype=np.uint8)
img.fill(0)
print(img)
You can also list all pixels
umpy as np # Import NumPy for array creation and manipulation
from PIL import Image # Import Image module (not used directly here)
import matplotlib.pyplot as plt # Import matplotlib for image display (not used here)
img = np.zeros([1,1,3], dtype=np.uint8) # Create a 1×1 RGB image array initialized to zeros
img.fill(0) # Fill the array with 0 (black pixel)
height, width, _ = img.shape # Loop over each row (y-coordinate)
for y in range(height): # Loop over each row (y-coordinate)
for x in range(width): # Loop over each column (x-coordinate)
print(img[y, x]) # Print the pixel value at position (y, x), this is typically an array like [R, G, B]
plt.imshow(img) # Display the image using matplotlib
plt.title(“Example”) # Add a title to the image
plt.axis(‘off’) # Turn off axis ticks and labels
plt.show() # Render the image on the screen
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
img = np.zeros([1,1,3],dtype=np.uint8)
img.fill(0)
height, width, _ = img.shape
for y in range(height):
for x in range(width):
print(img[y, x])
plt.imshow(img)
plt.title("Example")
plt.axis('off')
plt.show()
Converting Images Into Arrays
The following opens an image file using Pillow, converts the image into a NumPy array so its pixel values can be processed numerically, and then prints the resulting array.
from PIL import Image # Import Image class from Pillow to work with image files
import numpy as np # Import NumPy for numerical array operations
img = Image.open(‘example.png’) # Open the image file and load it as a PIL Image object
img_array = np.array(img) # Convert the image into a NumPy array (pixel values)
print(img_array) # Print the array representing the image pixels
from PIL import Image
import numpy as np
img = Image.open('example.png')
img_array = np.array(img)
print(img_array)
Create Random Image
Creates and shows a tiny, randomly colored image
umpy as np # Import NumPy for array creation and manipulation
from PIL import Image # Import Image module (not used directly here)
import matplotlib.pyplot as plt # Import matplotlib for image display (not used here)
pixel_rgb = np.random.randint(0,256, size=(10,10,3)) # Generate a 10×10 image with random RGB values, np.random.randint(0,256, size=(10,10,3)) creates integers from 0 to 255 for each RGB channel
plt.imshow(pixel_rgb) # Show the image from the pixel array
plt.title(“Example”) # Add a title to the image
plt.axis(‘off’) # Hide the axes for a cleaner display
plt.show() # Render the image on screen
import numpy as np
import matplotlib.pyplot as plt
pixel_rgb = np.random.randint(0,256, size=(10,10,3))
plt.imshow(pixel_rgb)
plt.title("Example")
plt.axis('off')
plt.show()
Cybersecurity – Example 1 (Network Traffic Analysis)
You use the np.mean() function to detect unusual spikes, which might indicate a DDoS attack
import numpy as np # Import the NumPy library and give it the alias ‘np’
packets_per_second = np.array([1000, 50, 100, 120, 500, 115000]) # Calculate the average (mean) number of packets per second
print(“Average packets per second:”, np.mean(packets_per_second)) # Print the calculated average with a descriptive message
import numpy as np
packets_per_second = np.array([1000, 50, 100, 120, 500, 115000])
print("Average packets per second:", np.mean(packets_per_second))
Cybersecurity – Example 2 (Login Attempts Monitoring)
You use the np.mean() function to track failed login attempts to detect brute force attacks
import numpy as np # Import the NumPy library and give it the alias ‘np’
failed_logins = np.array([10, 2, 0, 1, 1, 0,4]) # Calculate the average (mean) number of failed login
print(“Average failed logins per hour:”, np.mean(failed_logins)) # Print the calculated average with a descriptive message
import numpy as np
failed_logins = np.array([10, 2, 0, 1, 1, 0,4])
print("Average failed logins per hour:", np.mean(failed_logins))
Cybersecurity – Example 3 (CPU/Memory Usage Monitoring)
You use the np.mean() function to track failed login attempts to detect unusual resource usage
import numpy as np # Import the NumPy library and give it the alias ‘np’
high_usage = np.array([2, 8, 10, 95, 10]) # Calculate the average (mean) number of failed login
print(“Average CPU usage:”, np.mean(high_usage)) # Print the calculated average with a descriptive message
import numpy as np
high_usage = np.array([2, 8, 10, 95, 10])
print("Average CPU usage:", np.mean(high_usage))