Lists, Arrays, Numpy Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

02/01/2025, 05:22 NumPy.

ipynb - Colab

‫اللهم ال سهل إال ما جعلته سهال وأنت تجعل الصعب إن شئت سهال‬

‫اللهم ارزقنا الفهم‬

keyboard_arrow_down Let's Start our story with Python Lists


Lists used for store multiple/ collection of elements.

Python Lists are:-

Ordered/ Indexing
Mutable
Heterogeneous >> Store Different Data Types
Dynamic >> Size is changable >> Lists can grow or shrink as needed

keyboard_arrow_down 1. Creating a list


# 1.1 Using Square Brackets []

# First Initialize empty list


my_list = []
# Filling the list with elements
my_list = ['Ahmed', 'Sara', 1, 303]
my_list

['Ahmed', 'Sara', 1, 303]

# OR you can skip the step of initialization and put elements direct <as u like>
my_list1 = ['Ahmed', 'Sara', 1, 303]
my_list1

['Ahmed', 'Sara', 1, 303]

# 1.2 Creating a list Using list() constructor


my_list2 = list(('Ahmed', 'Sara', 1, 303)) # >> We used douple parentheses!!
my_list2

['Ahmed', 'Sara', 1, 303]

''' Why we used douple parentheses in the previous step not just only one??
Try to code this and check the output:

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 1/21
02/01/2025, 05:22 NumPy.ipynb - Colab
my_list2 = list('Ahmed', 'Sara', 1, 303)
'''

' Why we used douple parentheses in the previous step not just only one??\nTry to cod

''' Now let's explore this line >> my_list2 = list(('Ahmed', 'Sara', 1, 303))
1. The inner parentheses () define a tuple ('Ahmed', 'Sara', 1, 303)
2. The list() constructor takes this tuple as a single argument
3. It converts the tuple into a list: ['Ahmed', 'Sara', 1, 303]'''

' Now let's explore this line >> my_list2 = list(('Ahmed', 'Sara', 1, 303))\n1. The i
nner parentheses () define a tuple ('Ahmed' 'Sara' 1 303)\n2 The list() construct

# The douple parentheses not special

# We can use range


my_list3 = list(range(1,5))
my_list3

[1, 2, 3, 4]

# We can use a set


my_list4 = list({'Ahmed', 'Sara', 1, 303}) # Sets removes duplicates so when we creating a
my_list4

['Sara', 303, 1, 'Ahmed']

my_list5 = list({'Ahmed', 'Ahmed', '12','Sara', 1, 303})


my_list5

['Sara', 1, 'Ahmed', '12', 303]

2. Accessing an element by Indexing or Slicing ''Range of


keyboard_arrow_down Indexes''
# Access elements by Indexing >> 2 ways by the index of the 1st element 0 or by the index
my_list6 = ['a', 'b', 'c', 0, 'd', 101,'e']
print(my_list6[1])
print(my_list6[-3]) # Negative Indexing

b
d

# Access elements by slicing [start:end+1]


my_list6[1:5] # >> That will access from element with Index 1 to the element with Index 4

['b', 'c', 0, 'd']

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 2/21
02/01/2025, 05:22 NumPy.ipynb - Colab
# my_list6[0:4] Instead of write that to access from the 1st element u can use the next li
my_list6[:4] # >> That will access from element with Index 0 to the element with Index 3

['a', 'b', 'c', 0]

my_list6[2:] # >> That will access from element with Index 2 to the last element

['c', 0, 'd', 101, 'e']

# You can also use negative indexing here


my_list6[-4:-1] # >> That will access from element with Index -4 to the element with Index

[0, 'd', 101]

keyboard_arrow_down 3. Adding elements to the list


1. .append(): Adds a single element at the end
2. .extend(): Adds multiple elements at the end
3. .insert(): Adds an element at a specified position

my_list7 = ['a', 'b', 'c', 0, 'd', 101,'e']


my_list7.append("False")
my_list7

['a', 'b', 'c', 0, 'd', 101, 'e', 'False']

my_list7.extend([11, 'g'])
my_list7

['a', 'b', 'c', 0, 'd', 101, 'e', 'False', 11, 'g']

my_list7.insert(2, 'a') # Insert Ahmed at the index 2 and shift the other elements that wa
my_list7

['a', 'b', 'a', 'c', 0, 'd', 101, 'e', 'False', 11, 'g']

keyboard_arrow_down 4. Removing elements from the list


1. .remove(): Removes the first occurrence of a value
2. .pop(): Removes an element by index (default: last element)
3. .del: Deletes an element by index or the entire list
4. .clear(): Removes all elements from the list

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 3/21
02/01/2025, 05:22 NumPy.ipynb - Colab
my_list7.remove('a') # Removes the first occurrence of the value 'a'
my_list7

['b', 'a', 'c', 0, 'd', 101, 'e', 'False', 11, 'g']

my_list7.pop() # Removes the last element that is with index -1 : 'g'


my_list7

['b', 'a', 'c', 0, 'd', 101, 'e', 'False', 11]

my_list7.pop(2) # Removes the element with index 2 : 'Ahmed'


my_list7

['b', 'a', 0, 'd', 101, 'e', 'False', 11]

l0 = my_list7.pop(0) # >> What should be the value of the variable l0? what had been stored

l0

'b'

my_list7

['a', 0, 'd', 101, 'e', 'False', 11]

# Ok what about del() method?


del my_list7[-2] # Removes the element with index -2 : 'False'
my_list7

['a', 0, 'd', 101, 'e', 11]

# del my_list7 # Deletes the entire list

my_list7.clear() # Removes all elements from the list


my_list7

[]

5. Operations on lists

keyboard_arrow_down 1. Joining/ Concatenation & Repeating lists


# Joining lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = list1 + list2
list3
https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 4/21
02/01/2025, 05:22 NumPy.ipynb - Colab
list3

[1, 2, 3, 'a', 'b', 'c']

He put the 1st list elements, then the second one elements

# Repeating lists >> list* num of times u want to repeat it


list4 = list1 * 3
list4

[1, 2, 3, 1, 2, 3, 1, 2, 3]

keyboard_arrow_down 2. Sorting and Reversing


# Sorting >> Arranging elements of list that is by .sort() method
numbers = [34, 23, 67, 100, 88, 2]
numbers.sort()
numbers

[2, 23, 34, 67, 88, 100]

By default it sorts in an ascending order == from smaller to bigger elements

# Sorting in descending order


numbers.sort(reverse=True) # by making the argument reverse = True
numbers

[100, 88, 67, 34, 23, 2]

# Reversing >> reverse the order of a list by reverse() method


numbers.reverse()
numbers

[2, 23, 34, 67, 88, 100]

keyboard_arrow_down 3. Iterating through lists


# 1. You can loop through the list items by using a for loop
for x in numbers:
print(x*2)

4
46
68
134
176
200

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 5/21
02/01/2025, 05:22 NumPy.ipynb - Colab
# 2. Using enumerate() function
avengers = ['Iron Man', 'Captain America', 'Thor', 'Hulk']
for index, value in enumerate(avengers):
print(index, value)

0 Iron Man
1 Captain America
2 Thor
3 Hulk

By default it starts from 0 indexing and u can change it as u like

avengers = ['Iron Man', 'Captain America', 'Thor', 'Hulk']


for index, value in enumerate(avengers, start=1):
print(index, value)

1 Iron Man
2 Captain America
3 Thor
4 Hulk

# Understanding enumerate function more


avengers = ['Iron Man', 'Captain America', 'Thor', 'Hulk']
e = enumerate(avengers)
print(type(e))

<class 'enumerate'>

e_list = list(e)
print(e_list)

[(0, 'Iron Man'), (1, 'Captain America'), (2, 'Thor'), (3, 'Hulk')]

# 3. Using zip() function >> this function takes the 1st element from the 1st list with th
avengers = ['Iron Man', 'Captain America', 'Thor', 'Hulk']
names = ['Tony Stark', 'Steve Rogers', 'Thor Odinson', 'Bruce Banner']
z = zip(avengers, names)
print(type(z))

<class 'zip'>

z_list = list(z)
print(z_list)

[('Iron Man', 'Tony Stark'), ('Captain America', 'Steve Rogers'), ('Thor', 'Thor Odins

# Using for loop for iterating over the zip object


avengers = ['Iron Man', 'Captain America', 'Thor', 'Hulk']
names = ['Tony Stark', 'Steve Rogers', 'Thor Odinson', 'Bruce Banner']
for avenger, name in zip(avengers, names):
print(avenger, name)

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 6/21
02/01/2025, 05:22 NumPy.ipynb - Colab

Iron Man Tony Stark


Captain America Steve Rogers
Thor Thor Odinson
Hulk Bruce Banner

# Print zip with * >> the splat operator to print all the elements!
avengers = ['Iron Man', 'Captain America', 'Thor', 'Hulk']
names = ['Tony Stark', 'Steve Rogers', 'Thor Odinson', 'Bruce Banner']
z = zip(avengers, names)
print(*z)

('Iron Man', 'Tony Stark') ('Captain America', 'Steve Rogers') ('Thor', 'Thor Odinson'

Start coding or generate with AI.

keyboard_arrow_down Python Arrays


1. Python doesn't have built-in support for Arrays, but Python Lists can be used instead.
2. Array has multiple elements but with the same type, and that is a difference with the list.
3. Advantage: Array like list >> doesn't have fixed size, you can expand or shrink it.
4. Like list, array is indexed.
5. Arrays are best for numeric data and require the specification of a data type.

keyboard_arrow_down 1. Creating python Array


# We can use arrays in python by calling array module
import array as arr
# Syntax: array(typecode, [initializers])
# typecode like >> 'i' for Integer , 'f' for Float , 'd' for Double , 'u' for Unicode char

int_arr = arr.array('i', [1, 2, 3])


int_arr

array('i', [1, 2, 3])

# You can access to any element in array by index


int_arr[0]

keyboard_arrow_down 2. Operations on Arrays


https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 7/21
02/01/2025, 05:22 NumPy.ipynb - Colab

# Arrays support many operations, similar to lists but are limited to homogeneous data.
# 2.1 Adding elements to an array
int_arr.append(4) # Adding single element by append
int_arr

array('i', [1, 2, 3, 4])

int_arr.extend([5, 6]) # Adding multiple elements or you can say that you add array to the
int_arr

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

int_arr.insert(0, 5) # Adding an element to a specific location


int_arr

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

# 2.2 Removing elements from array


int_arr.pop() # Removes the last element >> 6
int_arr

array('i', [5, 1, 2, 3, 4, 5])

int_arr.remove(5) # Removes the first occurrence of the value 5


int_arr

array('i', [1, 2, 3, 4, 5])

del int_arr[1] # delete element from a specific location

int_arr

array('i', [1, 3, 4, 5])

# 2.3 Slicing elements


int_arr[1:3] # >> slice/ select elements from the element that has index 1 and the element
# Doesn't take the element in index 3 in consider

array('i', [3, 4])

int_arr[:3] # >> slice/ select elements from the element that has index 0 to the element t
# Doesn't take the element in index 3 in consider

array('i', [1, 3, 4])

int_arr[2:] # >> slice/ select elements from the element that has index 2 to the last elem

array('i', [4, 5])

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 8/21
02/01/2025, 05:22 NumPy.ipynb - Colab
# 2.4 Changing array's element
int_arr[0] = -1 # changing the value of the 1st element to be -1 instead of 1
int_arr

array('i', [-1, 3, 4, 5])

int_arr[1:] = arr.array('i', [-2, -3, -4]) # changing the value of multiple elements
int_arr

array('i', [-1, -2, -3, -4])

Numpy

Why Numpy and how does it difference from python lists?

Speed: Numpy is very fast and python lists are very slow. ::: NumPy operations are
implemented in C, enabling faster execution compared to native Python loops and
lists.

Memory Efficient: NumPy arrays are more memory-efficient than Python lists
because they store data in contiguous memory locations and use a fixed data type
for all elements.

In python lists we can do operations like: Insertion, deletion, appending,


concatenation ::: In Numpy you can do all that operations and mooore

Numpy provides Advanced Mathematical and Statistical Functions for:

1. Linear algebra
2. Statistical analysis (mean, median, mode)
3. Mathematical functions

Python lists are primarily support 1D arrays ::: At the other side Numpy supports
multi-dimensional arrays, enabling powerful operations on matrices and tensors.

NumPy is the backbone of many other Python libraries, like: Pandas, SciPy, Scikit-
learn

keyboard_arrow_down 1. Load Numpy package


# We use np as a shortcut rather than writing numpy at each time we call numpy package
import numpy as np

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=jx… 9/21
02/01/2025, 05:22 NumPy.ipynb - Colab

keyboard_arrow_down 2. Creating Arrays


# 1.1 1D Array
# Numpy as a vector >> as a row
a = np.array([1, 2, 3, 4, 5])
a

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

# 1.2 2D Array
c = np.array([[1, 2, 3], [4, 5, 6]])
c

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

# Numpy as a vector >> as a column


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

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

Even if there is only one column, as long as there are multiple dimensions, it is considered 2D.

[ [1],

[2],

[3],

[4],

[5] ]

# 1.3 Multi Dimensional Array >> Tensors


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

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

[[-1, -2, -3],


[-4, -5, -6]]])

# Discover the shape of the multi dim array : d , by .shape attribute


d.shape

(2, 2, 3)

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 10/21
02/01/2025, 05:22 NumPy.ipynb - Colab

(2, 2, 3) >> 2 matrices, 2 rows, 3 columns

keyboard_arrow_down Initializing arrays Automaticilly


z = np.arange(1, 10, 2) # Start at 1, stop before 10, step by 2
z

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

# All zero matrix


np.zeros((2, 3)) # 2 rows, 3 columns

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


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

# All one matrix


np.ones((2, 2, 3))

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


[1., 1., 1.]],

[[1., 1., 1.],


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

# with specifing dtype


np.ones((4, 2, 2), dtype='int32')

array([[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]],

[[1, 1],
[1, 1]]], dtype=int32)

# Any other number


np.full((2, 2), 99)

array([[99, 99],
[99, 99]])

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

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 11/21
02/01/2025, 05:22 NumPy.ipynb - Colab

# creating an array (full_like)


np.full_like(c, 4)

array([[4, 4, 4],
[4, 4, 4]])

# Another way!
np.full(c.shape, 4)

array([[4, 4, 4],
[4, 4, 4]])

# Random decimal numbers


np.random.rand(4, 2, 2)

array([[[0.55595524, 0.99336253],
[0.0704707 , 0.95317059]],

[[0.74502318, 0.42871848],
[0.97169651, 0.65316088]],

[[0.70029031, 0.13333858],
[0.71847773, 0.08011527]],

[[0.52686587, 0.29535199],
[0.46681343, 0.90753534]]])

# Random numbers (random_sample)


np.random.random_sample(c.shape)

array([[0.04480137, 0.53875628, 0.45652441],


[0.49653584, 0.94224151, 0.20062437]])

# Random Integer numbers


np.random.randint(5, size = (3, 3))

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

np.random.randint(4, 6, size = (3, 3))

array([[5, 5, 5],
[5, 5, 5],
[5, 4, 5]])

# Identity matrix
np.identity(5)

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


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

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 12/21
02/01/2025, 05:22 NumPy.ipynb - Colab

# Repeat array
arr = np.array([[1, 2, 3]])
r1 = np.repeat(arr, 3, axis = 0) # >> repeat arr on 0(x) axis 3 times
print(r1)

[[1 2 3]
[1 2 3]
[1 2 3]]

r2 = np.repeat(arr, 3, axis = 1) # >> repeat arr on 1(y) axis 3 times


print(r2)

[[1 1 1 2 2 2 3 3 3]]

keyboard_arrow_down 3. Get Dimensions of an array


# For 1D array
a.shape

(5,)

The output of (num,) represents the output of shape 1D array, num indicates number of elements
in the array.

# For 2D array
b.shape

(5, 1)

b: It is a 2D array because it has two dimensions:

1. Rows: There are 5 rows (one for each list element).


2. Columns: There is 1 column (each inner list contains a single element).

c.shape # 2D array

(2, 3)

# For multi Dimensional array


d.shape # and we explained above the output

(2, 2, 3)

keyboard_arrow_down 4. Get Type


https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 13/21
02/01/2025, 05:22 NumPy.ipynb - Colab

a.dtype

dtype('int64')

# We can also change the type as we want


a = np.array([1, 2, 3, 4, 5], dtype='int16')
a.dtype

dtype('int16')

keyboard_arrow_down 5. Get Size


# 5.1 Understand the memory usage of individual elements in the array
a.itemsize

As we set the dtype of a int16: itemsize is the size of a single array element in
bytes.

So the size of each int16 element in a takes = 16 / 8 = 2 bytes

# 5.2 Calculate the total count of elements


a.size

# 5.3 Calculate the total size


total_size = a.size * a.itemsize
total_size

10

# Another way to calculate the total size


total_size = a.nbytes
total_size

10

keyboard_arrow_down 6...etcAccess/ change a specific elements, rows, columns

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 14/21
02/01/2025, 05:22 NumPy.ipynb - Colab
x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
x

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

# 6.1 Get a specific element >> name_of_array[index_of_row, index_of_column]


x[1, 4]

10

# 6.2 Get a specific row


x[0, :] # >> 1st row with all elements in it

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

# 6.3 Get a specific column


x[:, -1] # Get the last column with all elements in it

array([ 5, 10])

# 6.4 Specifing elements [startIndex : endIndex : stepSize]


x[1, 0: 5: 2]

array([ 6, 8, 10])

# 6.4 Changing the value of an element


x[0, 4] = -1
x

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

# 6.5 Changing the values of entire column


x[:, 2] = 0
x

array([[ 1, 2, 0, 4, -1],
[ 6, 7, 0, 9, 10]])

With 3D

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

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

[[-1, -2, -3],


[-4, -5, -6]]])

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 15/21
02/01/2025, 05:22 NumPy.ipynb - Colab
# 6.A Get a specific element
y[0, 1, 2] # >> 1st matrix, 2nd row, 3rd column

# 6.B Get a specification of elements


y[:, 1, :] # >> 2nd row of all matrices

array([[ 4, 5, 6],
[-4, -5, -6]])

y[:, 0, 0] # >> 1st element of all matrices

array([ 1, -1])

# 6.C Replace elements


y[:, 1, :]

array([[ 4, 5, 6],
[-4, -5, -6]])

y[:, 1, :] = [[9, 9, 9], [8, 8, 8]]


y

array([[[ 1, 2, 3],
[ 9, 9, 9]],

[[-1, -2, -3],


[ 8, 8, 8]]])

keyboard_arrow_down 7. Copying arrays


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

array([1, 2, 3])

b[0] = 100
b

array([100, 2, 3])

array([100, 2, 3])

a = np.array([1, 2, 3])
b = a.copy()
b

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 16/21
02/01/2025, 05:22 NumPy.ipynb - Colab

array([1, 2, 3])

b[0] = 100
b

array([100, 2, 3])

array([1, 2, 3])

keyboard_arrow_down 8. Mathematics
a = np.array([1, 2, 3, 4])
a

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

a +=2
a

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

a -=2
a

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

a*=2
a

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

a / 2
a

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

a ** 2

array([ 4, 16, 36, 64])

# Take sin
np.sin(a)

array([ 0.90929743, -0.7568025 , -0.2794155 , 0.98935825])

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 17/21
02/01/2025, 05:22 NumPy.ipynb - Colab
# Take cos
np.cos(a)

array([-0.41614684, -0.65364362, 0.96017029, -0.14550003])

b = np.array([1, 0, 1, 0])
a + b

array([3, 4, 7, 8])

keyboard_arrow_down 9. Linear Algebra


a = np.ones((2, 3))
print(a)

b = np.full((3, 2), 2)
print(b)

[[1. 1. 1.]
[1. 1. 1.]]
[[2 2]
[2 2]
[2 2]]

# Multiply a and b
np.matmul(a, b)

array([[6., 6.],
[6., 6.]])

# Or you can do that by this way


a @ b

array([[6., 6.],
[6., 6.]])

# Find the determinant


c = np.identity(3)
np.linalg.det(c)

1.0

# Vector norm >> distance


from numpy.linalg import norm

a = np.array([1, 2, 3])
norm1 = norm(a, 1) # 1 is for l1 norm >> calc its sum of the absolute values
norm1

6.0

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 18/21
02/01/2025, 05:22 NumPy.ipynb - Colab

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


norm1 = norm(a, 1)
norm1

6.0

norm2 = norm(a, 2) # 2 is for l2 norm >> calc its distance from the origin, it cal by squa
norm2

3.7416573867739413

# default is l2 if we doesn't specify


norm3 = norm(a)
norm3

3.7416573867739413

keyboard_arrow_down 10. Statistics


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

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

np.min(stats)

axis=0: Compute the minimum along columns.

axis=1: Compute the minimum along rows.

np.min(stats, axis = 0)

array([1, 2, 3])

np.min(stats, axis = 1)

array([1, 4])

np.max(stats)

np.max(stats, axis = 0)

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 19/21
02/01/2025, 05:22 NumPy.ipynb - Colab

array([4, 5, 6])

np.sum(stats)

21

np.sum(stats, axis = 0)

array([5, 7, 9])

keyboard_arrow_down 11. Reshape Arrays


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

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

after = before.reshape((2, 2, 2))


after

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

[[5, 6],
[7, 8]]])

keyboard_arrow_down 12. Stacking vectors


Stacking vectors refers to combining multiple vectors (1D arrays) into a higher-dimensional array
in NumPy. This operation is typically used to create 2D or higher-dimensional arrays by aligning
vectors along rows, columns, or other axes.

# Horizontal Stacking
v1 = np.array([1, 2, 3, 4])
v2 = np.array([5, 6, 7, 8])

np.hstack([v1, v2, v2])

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

# Vertical Stacking
v1 = np.array([1, 2, 3, 4])
v2 = np.array([5, 6, 7, 8])

np.vstack([v1, v2, v2, v1])

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 20/21
02/01/2025, 05:22 NumPy.ipynb - Colab

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

References:
W3scools

GeeksforGeeks

Python NumPy Tutorial for Beginners YT video

https://colab.research.google.com/drive/1iMtDnMQhTzqanKqjr0NtF7MgUa47dQnk#scrollTo=j… 21/21

You might also like