Numpy Full Tutorial
Numpy Full Tutorial
md 8/23/2025
NumPy is an open source Python library that’s widely used in science and engineering.
It is the fundamental package for scientific computing in Python.
It provides a multidimensional array object.
NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of
data. Typically, such operations are executed more efficiently and with less code than is possible using
Python’s built-in sequences.
[Link]
Installing NumPy
Importing NumPy
import numpy as np
1 / 37
Numpy Full [Link] 8/23/2025
1D-Array
[Link]
# Creating a 1D-array
a = [Link]([5, 7, 2, 3, 8])
a
array([5, 7, 2, 3, 8])
Checking the type of Numpy array (data type of the elements inside the array):
ndarray: Core NumPy class for N-dimensional arrays
type(a)
[Link]
we can access an individual element of this array as we would access an element in the original list:
using the integer index of the element within square brackets.
NumPy arrays are “0-indexed”: the first element of the array is accessed using index 0, not 1.
2) Slicing:
Indexing:
2 / 37
Numpy Full [Link] 8/23/2025
a[0]
a[0] = 10
a
array([10, 7, 2, 3, 8])
Slicing:
Using: array_name[start:stop:step]
Note:
step may not be specified
array([10, 7, 2])
array([10, 7, 2, 3, 8])
3 / 37
Numpy Full [Link] 8/23/2025
array([10, 2, 8])
[1, 2, 3, 4, 5]
[ 1 99 3 4 5]
Conclusion:
Slicing a Python list ➝ returns a copy.
Slicing a NumPy array ➝ returns a view.
2D-Array:
A two-dimensional array would be like a table:
[Link]
Two and higher-dimensional arrays can be initialized from nested Python sequences:
4 / 37
Numpy Full [Link] 8/23/2025
array([[1, 5, 2, 0],
[8, 3, 6, 1],
[1, 7, 2, 9]])
# Another way
b[1,3] # 1 → element in 2nd row, 4th column
Slicing:
Slicing 2D-Array:
5 / 37
Numpy Full [Link] 8/23/2025
array([[5, 2],
[3, 6]])
array([5, 3, 7])
array([1, 7, 2, 9])
array([[2, 9]])
3D-Array:
Array that has three dimensions (or axes).
In the context of machine learning and deep learning, a 3D array is also known as a 3rd-order tensor
or simply a tensor of rank 3.
[Link]
6 / 37
Numpy Full [Link] 8/23/2025
c = [Link]([
[[5, 16, 0], [4, 5, 6], [8, 1, 9]], # First 3x3 matrix
[[10, 23, 15], [2, 14, 15], [1, 22, 14]], # Second 3x3 matrix
[[4, 10, 6], [17, 0, 12], [5, 56, 13]] # Third 3x3 matrix
])
c
[[ 4, 10, 6],
[17, 0, 12],
[ 5, 56, 13]]])
array_name [layer_index][row_index][column_index]
c[0,1,2] # Accessing element in 3rd column of 2nd row in 1st Layer, Output: one
number (Scalar)
# Another way
c[0][1][2] # Accessing element in 3rd column of 2nd row in 1st Layer
7 / 37
Numpy Full [Link] 8/23/2025
Slicing:
array([[16, 5, 1],
[23, 14, 22],
[10, 0, 56]])
Slicing a Sub-Matrix:
c[0, 0:2, 0:2] # getting the 1st and 2nd rows and cols from the First Layer
array([[ 5, 16],
[ 4, 5]])
Array Attributes
ndim: Number of dimensions of array.
8 / 37
Numpy Full [Link] 8/23/2025
shape: Tuple of non-negative integers that specify the number of elements along each dimension.
size: Total number of array elements.
dtype: Data type of the array elements.
itemsize: Size (in bytes) of each element.
nbytes : Total memory consumed (in bytes),
nbytes = Total [Link] elements * size of element in array.
print(a)
[10 7 2 3 8]
(5,)
len([Link]) == [Link]
True
Note:
So for any NumPy array: len([Link]) is always equal to [Link].
9 / 37
Numpy Full [Link] 8/23/2025
[Link]
dtype('int32')
Remember:
All elements of numpy array must be of the same data type.
dtype('int32')
dtype('float64')
dtype('<U4')
Mixed Arrays:
NumPy will automatically upcast the elements to a common data type that can represent all the
values. This process is called Type Promotion.
10 / 37
Numpy Full [Link] 8/23/2025
dtype('float64')
dtype('<U11')
dtype('float64')
dtype('int32')
print(b)
[[1 5 2 0]
[8 3 6 1]
[1 7 2 9]]
[Link] # b is 2D-Array
11 / 37
Numpy Full [Link] 8/23/2025
(3, 4)
12
True
[Link]
dtype('int32')
[Link]
48
12 / 37
Numpy Full [Link] 8/23/2025
[Link](): Creates an array without initializing entries (values are random values)
[Link](): Creates num evenly spaced values from start to stop (inclusive).
[Link](shape):
[Link](3)
[Link]((2,3))
[Link](shape):
[Link]((3,3))
[Link](shape):
array([0., 0.])
[Link]((2,3))
Important Notes:
The function empty creates an array whose initial content is random and depends on the state
of the memory.
The reason to use empty() over zeros() and ones() is speed.
[Link](range_of_elements):
array([0, 1, 2, 3])
array([3, 5, 7, 9])
14 / 37
Numpy Full [Link] 8/23/2025
[Link](2)
array([1., 1.])
x = [Link](2, dtype=np.int64)
x
2. [Link]():
15 / 37
Numpy Full [Link] 8/23/2025
[0 2 1]
Final Sorted Array: [10 20 30]
3. [Link]():
print(sorted_idx) # [1 3 2 0]
print(names[sorted_idx]) # ['Jane' 'Jane' 'Tom' 'Tom']
print(grades[sorted_idx]) # [99 9 85 90]
[0 1 3 2]
['Alaa' 'Mirna' 'Sara' 'Youness']
[99 98 90 85]
4. [Link]():
Finds the index where elements should be inserted to maintain order in a sorted array.
[2 3]
16 / 37
Numpy Full [Link] 8/23/2025
5. [Link]():
Rearranges the array so that the element that would be in the specified position (specified index) if
the array was fully sorted, is placed in that position.
The numbers before it are smaller or equal, the numbers after it are larger or [Link] it does not sort
the entire array.
[1 2 6 9 7]
Concatenating Arrays
Joining two or more arrays along an existing axis (does not add a new dimension).
Arrays must have the same shape except along the axis you concatenate on.
Conatenating 1D Arrays:
x = [Link]([1, 2, 3, 4])
y = [Link]([5, 6, 7, 8])
[Link]((x, y))
array([1, 2, 3, 4, 5, 6, 7, 8])
The shapes must match except for the axis you're concatenating on.
17 / 37
Numpy Full [Link] 8/23/2025
array([[1, 2],
[3, 4],
[5, 6]])
array([[1, 2, 5],
[3, 4, 6]])
Stacking Arrays
Joining arrays along a new axis (adds a new dimension).
s1 = [Link]([[1, 1],
[2, 2]])
s2 = [Link]([[3, 3],
[4, 4]])
array([[1, 1],
[2, 2],
[3, 3],
[4, 4]])
[[1 1 3 3]
[2 2 4 4]]
[[3 7]
[4 8]]]
19 / 37
Numpy Full [Link] 8/23/2025
Splitting Arrays
The opposite of concatenating or stacking.
[Link]():
You must provide a number of splits that divides the array evenly.
np.array_split():
Equivalent to [Link](axis=1)
20 / 37
Numpy Full [Link] 8/23/2025
[array([[1],
[4]]),
array([[2],
[5]]),
array([[3],
[6]])]
Equivalent to [Link](axis=0)
[array([[[1],
[3]],
[[5],
[7]]]),
array([[[2],
[4]],
[[6],
[8]]])]
Reshaping Arrays
Reshaping means changing the shape (dimensions) of a NumPy array without changing its data.
When you use the reshape method, the array you want to produce needs to have the same number of
elements as the original array.
21 / 37
Numpy Full [Link] 8/23/2025
If you start with an array with 12 elements, you’ll need to make sure that your new array also has a total
of 12 elements.
arr = [Link](6)
resh_arr = [Link](3, 2)
Original Array: [0 1 2 3 4 5]
Reshaped Array: [[0 1]
[2 3]
[4 5]]
Default Reshaping
NumPy calculates the appropriate dimension that fits the data by passing the number of rows you want
and then -1.
Transposing Arrays
22 / 37
Numpy Full [Link] 8/23/2025
Reversing or changing the axes of an array according to the values you specify.
Using:
array_name.transpose()
array_name.T
array([[0, 1, 2],
[3, 4, 5]])
transposed_arr = [Link]()
# Another way
arr.T
array([[0, 3],
[1, 4],
[2, 5]])
Reversing Arrays
23 / 37
Numpy Full [Link] 8/23/2025
[Link](): function allows you to flip, or reverse, the contents of an array along an axis.
Note:
When using [Link](), specify the array you would like to reverse and the axis. If you don’t specify
the axis, NumPy will reverse the contents along all of the axes of your input array.
Reversing 1D Array:
# Reversing Array
reversed_arr = [Link](arr_1d)
print("Reversed 1D Array:", reversed_arr)
Reversing 2D Array:
Reversing the content in all of the rows and all of the columns.
# Reversing Array
reversed_arr_2d = [Link](arr_2d)
print("Reversed 2D Array \n", reversed_arr_2d)
24 / 37
Numpy Full [Link] 8/23/2025
[[ 9 10 11 12]
[ 5 6 7 8]
[ 1 2 3 4]]
[[ 4 3 2 1]
[ 8 7 6 5]
[12 11 10 9]]
arr_2d[1] = [Link](arr_2d[1])
print(arr_2d)
[[ 1 2 3 4]
[ 8 7 6 5]
[ 9 10 11 12]]
arr_2d[:,1] = [Link](arr_2d[:,1])
print(arr_2d)
[[ 1 10 3 4]
[ 8 7 6 5]
[ 9 2 11 12]]
To prepare data for machine learning models that expect 1D input (Ex: logistic regression).
To pass image pixel data (Ex: 2D grayscale images) into a model as a flat vector.
2 Functions:
array_name.flatten(): Created a new array which is a reference to the parrent array (View).
Any changes to the new array will affect the parent array as well.
array_name.ravel(): Ddoes not create a copy, it’s memory efficient.
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Shape of Array: (3, 4)
Dim of Array: 2
[Link]()
When you use flatten, changes to your new array won’t change the parent array.
a1 = [Link]()
a1[0] = 99
print("New Array:", a1)
print("The original Array:\n", x) # Original array
26 / 37
Numpy Full [Link] 8/23/2025
a2 = [Link]()
a2[0] = 98
print("New Array:", a2)
print("Original Array:\n", x)
[Link] [Link]
# Creating Arrays
data = [Link]([1, 2])
ones = [Link](2, dtype=int)
print(ones)
[1 1]
[Link]
Result: [2 3]
27 / 37
Numpy Full [Link] 8/23/2025
# Subtraction
data - ones
array([0, 1])
# Multiplication
data * data
array([1, 4])
# Division
data / data
array([1., 1.])
[Link]
c1 = [Link]([1, 2, 3, 4])
print("Sum of all elements:", [Link]())
28 / 37
Numpy Full [Link] 8/23/2025
[[1 1]
[2 2]]
[3 3]
array([2, 4])
Aggregation Functions:
Used to summarize data.
[Link](): Total sum of elements
[Link](): Arithmetic mean
[Link](): Median (middle value)
[Link](): Standard deviation
[Link](): Variance
[Link](): Minimum value
[Link](): Maximum value
[Link](): Index of max element
[Link](): Index of min element
[Link](): Cumulative sum
[Link](): Cumulative product
Maximum Value: 3
Minimum Value: 1
Sum of array elements: 6
data_2d = [Link]([
[2, 4, 5],
[9, 14, 0],
[8, 9, 15]
])
29 / 37
Numpy Full [Link] 8/23/2025
You can specify on which axis you want the aggregation function to be computed.
array([2, 4, 0])
7.333333333333333
# Specifying axis
data_2d.mean(axis=0) # taking the mean across Cols
array([6.33333333, 9. , 6.66666667])
# Specifying axis
data_2d.mean(axis=1) # taking the mean across Rows
30 / 37
Numpy Full [Link] 8/23/2025
8.0
4.8074017006186525
23.11111111111111
# Cumulative Summation
[Link](data_2d) # taking each element and adding it to the previous one and so
one
31 / 37
Numpy Full [Link] 8/23/2025
# Cumulative Product
[Link](data_2d) # taking each element and multiplying it by the previous one
and so one
All the above functions uses Aggregation along Axes just by specifying the axis (axis=0 or axis=1)
BroadCasting Arrays
Powerful feature in NumPy that allows arithmetic operations on arrays of different shapes(without
explicitly replicating data).
It automatically expands the smaller array across the larger one so their shapes become compatible for
element-wise operations.
Important Rule:
The dimensions of your array must be compatible, for example, when the dimensions of both
arrays are equal or when one of them is 1. If the dimensions are not compatible, you will get a
ValueError.
Array * Scalar:
[Link]
NumPy broadcasts the scalar 1.6 to match the shape of data → [1.6, 1.6].
Note:
NumPy understands that the multiplication should happen with each cell (which is called
Broadcasting)
2D and 1D Arrays:
d1 = [Link]([[1, 2, 3],
[4, 5, 6]])
32 / 37
Numpy Full [Link] 8/23/2025
[[11 22 33]
[14 25 36]]
d3 = [Link]([[1, 2, 3],
[4, 5, 6]])
---------------------------------------------------------------------------
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
Python lists require looping through elements manually, which is slower, especially for large datasets.
This is why NumPy is preferred in data science, ML, and scientific computing.
import time
33 / 37
Numpy Full [Link] 8/23/2025
Accessing DocString
Every object contains the reference to a string, which is known as the docstring.
Docstring contains a quick and concise summary of the object and how to use it.
It will act as documentation for others (or for you later) to understand what the script is for
and how it works.
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
34 / 37
Numpy Full [Link] 8/23/2025
arr_1D?
Defining your function with Docstring then obtaining information about it:
Parameters:
x1 (int or float): The first number
x2 (int or float): The second number
Returns:
int or float: The result of (x1 + x2 + 2).
"""
return x1 + x2 + 2
operat?
35 / 37
Numpy Full [Link] 8/23/2025
At some point, you will want to save your arrays to disk and load them back without having to re-run
the code.
load() and save() functions can handle NumPy binary files with a .npy file extension, and a savez
function that handles NumPy files with a .npz file extension.
The .npy and .npz files store data, shape, dtype, and other information required to reconstruct the
ndarray in a way that allows the array to be correctly retrieved, even when the file is on another
machine with different architecture.
If you want to store a single ndarray object, store it as a .npy file using [Link]().
If you want to store more than one ndarray object in a single file, save it as a .npz file using
[Link]().
X = [Link]([1, 2, 3, 4, 5, 6])
[Link]('one_ndarray', X)
X_recons = [Link]('one_ndarray.npy')
X_recons
array([1, 2, 3, 4, 5, 6])
Saving a NumPy array as a plain text file like a .csv or .txt file with [Link]("[Link]",
array_name).
Then, You can quickly and easily load your saved text file using loadtxt():
[Link]('array_csv_file.csv')
36 / 37
Numpy Full [Link] 8/23/2025
37 / 37