Essential numpy before you start your Machine Learning journey in python.pdf

Smrati Kumar Katiyar
Smrati Kumar KatiyarWrite codes at askme.com um Getit Infoservices Pvt. Ltd.

This is a very quick tutorial in numpy for machine learnign and deep learning practitioner.

Essential numpy before you start your Machine
Learning journey in python
Linkedin: https://www.linkedin.com/in/smrati/
Twitter: https://twitter.com/SmratiKatiyar
importing numpy
Creating a numpy array
NumPy offers various ways to create arrays. Here are some of the different methods for creating
NumPy arrays:
1. Using Lists or Tuples:
You can create a NumPy array from a Python list or tuple.
2. Using NumPy Functions:
NumPy provides functions like np.zeros() , np.ones() , np.empty() , and np.full()
to create arrays filled with specific values.
import numpy as np
import numpy as np
# Create an array from a list
arr_from_list = np.array([1, 2, 3, 4, 5])
# Create an array from a tuple
arr_from_tuple = np.array((1, 2, 3, 4, 5))
import numpy as np
# Create an array of zeros
zeros_array = np.zeros(5)
# Create an array of ones
ones_array = np.ones(5)
# Create an empty array (initialized with random values)
empty_array = np.empty(5)
# Create an array filled with a specific value
3. Using Ranges:
You can create arrays with regularly spaced values using functions like np.arange() and
np.linspace() .
4. Using Random Data:
NumPy provides functions in the np.random module to generate arrays with random
data.
5. Using Identity Matrix:
You can create a 2D identity matrix using np.eye() .
6. Using Existing Data:
You can create a NumPy array from existing data, such as a Python list or another
NumPy array.
filled_array = np.full(5, 7) # Creates an array of 5 elements, each with
the value 7
import numpy as np
# Create an array with values from 0 to 4 (exclusive)
range_array = np.arange(0, 5)
# Create an array of 5 equally spaced values between 0 and 1 (inclusive)
linspace_array = np.linspace(0, 1, 5)
import numpy as np
# Create an array of random values between 0 and 1
random_array = np.random.rand(5)
# Create a 2D array of random integers between 1 and 100
random_int_array = np.random.randint(1, 101, size=(3, 3))
import numpy as np
# Create a 3x3 identity matrix
identity_matrix = np.eye(3)
import numpy as np
# Create an array from an existing list
existing_list = [1, 2, 3]
array_from_list = np.array(existing_list)
# Create an array from an existing NumPy array
These are some of the common ways to create NumPy arrays. Depending on your specific needs
and data, you can choose the most appropriate method for creating your array.
Element wise addition , subtraction , multiplication
and division
Output:
Numpy array and scalar interaction to each element
(known as broadcasting)
Output:
existing_array = np.array([4, 5, 6])
array_from_existing = np.array(existing_array)
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
plus = x + y
minus = x - y
mut = x * y
div = x / y
mod = y % x
print(plus)
print(minus)
print(mut)
print(div)
print(mod)
[5 7 9]
[-3 -3 -3]
[ 4 10 18]
[0.25 0.4 0.5 ]
[0 1 0]
import numpy as np
x = np.array([1, 2, 3])
print(x + 2)
[3 4 5]
Checking shape and datatype of numpy array
Output:
Matrix multiplication using numpy array
Output:
vector, matrix and tensor
In NumPy, you can represent vectors, matrices, and tensors using arrays. Here's an explanation of
the differences between these three concepts with NumPy examples:
1. Vector:
A vector is a one-dimensional array that represents a list of numbers or values. It has a
single row (or column) of elements.
In NumPy, you can create a vector using a 1D array.
import numpy as np
x = np.array([1, 2, 3])
y = np.array([1.7, 2, 3])
print(x.shape)
print(x.dtype)
print(y.dtype)
(3,)
int64
float64
import numpy as np
x = np.array([[1, 2, 3], [1, 2, 3]])
y = np.array([[1, 2], [1, 2], [1, 2]])
print(x.shape)
print(y.shape)
print(np.matmul(x, y))
(2, 3)
(3, 2)
[[ 6 12]
[ 6 12]]
import numpy as np
2. Matrix:
A matrix is a two-dimensional array where each element is identified by two indices (rows
and columns).
In NumPy, you can create a matrix using a 2D array.
3. Tensor:
A tensor is a multi-dimensional array with more than two dimensions. It can have three or
more dimensions.
In NumPy, you can create tensors using arrays with more than two dimensions.
In the examples above:
vector is a 1D NumPy array with shape (5,) .
matrix is a 2D NumPy array with shape (3, 3) .
tensor is a 3D NumPy array with shape (2, 2, 2) .
To summarize, the key difference between these concepts is their dimensionality:
Vectors are 1D arrays.
Matrices are 2D arrays.
Tensors are multi-dimensional arrays with three or more dimensions.
Broadcasting
Broadcasting in NumPy is a powerful feature that allows you to perform operations on arrays of
different shapes, making them compatible for element-wise operations without explicitly creating
new arrays to match their shapes. In simple terms, broadcasting helps NumPy "stretch" smaller
arrays to make them compatible with larger arrays, so you can perform operations on them
efficiently.
Here's a simplified explanation of broadcasting with an example:
Suppose you have two NumPy arrays:
# Creating a vector
vector = np.array([1, 2, 3, 4, 5])
import numpy as np
# Creating a matrix
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
import numpy as np
# Creating a tensor (3D example)
tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
1. Array A with shape (3, 3) :
2. Array B with shape (1, 3) :
Now, you want to add these two arrays together element-wise. Normally, you would need arrays
with the same shape for element-wise addition, but broadcasting allows you to perform this
operation without explicitly copying or reshaping the smaller array.
Here's how broadcasting works in this case:
1. NumPy identifies that the dimensions of the arrays are not the same.
2. It checks if the dimensions are compatible for broadcasting by comparing them from the right
side (trailing dimensions).
3. In this example, the dimensions are compatible because the size of the last dimension of
array B (which is 3) matches the size of the corresponding dimension in array A .
4. NumPy effectively "stretches" or "broadcasts" the smaller array B to match the shape of the
larger array A , making it look like this:
5. Now, NumPy can perform element-wise addition between the two arrays:
So, broadcasting allows you to perform operations between arrays of different shapes by
automatically making them compatible, without the need for manual reshaping or copying of data.
This makes your code more concise and efficient when working with NumPy arrays.
Access element in numpy arrays
Accessing elements in NumPy arrays is straightforward and involves specifying the indices of the
elements you want to retrieve. NumPy supports several ways to access elements, including basic
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [10, 20, 30]
B = [[10, 20, 30],
[10, 20, 30],
[10, 20, 30]]
Result = A + B = [[1+10, 2+20, 3+30],
[4+10, 5+20, 6+30],
[7+10, 8+20, 9+30]]
= [[11, 22, 33],
[14, 25, 36],
[17, 28, 39]]
indexing, slicing, and fancy indexing. Let's go through each of these methods:
1. Basic Indexing:
To access a single element in a NumPy array, you can use square brackets and specify
the row and column (or just a single index for 1D arrays).
2. Slicing:
You can access multiple elements or subarrays using slicing. Slicing allows you to specify
a range of indices.
3. Boolean Indexing (Fancy Indexing):
You can use boolean arrays to filter elements based on a condition.
4. Integer Array Indexing (Fancy Indexing):
You can use integer arrays to access elements by specifying the indices explicitly.
import numpy as np
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Access a single element
element = arr[0, 1] # Accesses the element at row 0, column 1 (value: 2)
import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5])
# Access a slice of elements
subarray = arr[2:5] # Retrieves elements from index 2 to 4 (values: [2, 3,
4])
# Access a subarray of a 2D array
subarray_2d = arr[1:3, 1:3] # Retrieves a 2x2 subarray from the original
2D array
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Create a boolean mask
mask = (arr % 2 == 0)
# Use the mask to access elements that meet the condition
even_numbers = arr[mask] # Retrieves elements [2, 4]
5. Negative Indexing:
You can use negative indices to access elements from the end of an array.
Remember that indexing in NumPy is zero-based, meaning the first element is accessed using
index 0. Additionally, indexing and slicing can be applied to both 1D and multidimensional (2D, 3D,
etc.) arrays, with different syntax for each dimension.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
# Create an array of indices
indices = np.array([1, 3])
# Use the indices to access specific elements
selected_elements = arr[indices] # Retrieves elements [20, 40]
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Access the last element using negative indexing
last_element = arr[-1] # Retrieves the last element (value: 5)

Recomendados

NUMPY-2.pptx von
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptxMahendraVusa
30 views91 Folien
NumPy.pptx von
NumPy.pptxNumPy.pptx
NumPy.pptxEN1036VivekSingh
157 views44 Folien
arraycreation.pptx von
arraycreation.pptxarraycreation.pptx
arraycreation.pptxsathya930629
8 views13 Folien
CAP776Numpy (2).ppt von
CAP776Numpy (2).pptCAP776Numpy (2).ppt
CAP776Numpy (2).pptChhaviCoachingCenter
4 views88 Folien
CAP776Numpy.ppt von
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.pptkdr52121
17 views88 Folien
Numpy - Array.pdf von
Numpy - Array.pdfNumpy - Array.pdf
Numpy - Array.pdfAnkitaArjunDevkate
130 views21 Folien

Más contenido relacionado

Similar a Essential numpy before you start your Machine Learning journey in python.pdf

NUMPY von
NUMPY NUMPY
NUMPY SharmilaChidaravalli
6.3K views24 Folien
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH... von
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...DineshThallapelly
5 views18 Folien
CE344L-200365-Lab2.pdf von
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
5 views1 Folie
Introduction to NumPy von
Introduction to NumPyIntroduction to NumPy
Introduction to NumPyHuy Nguyen
774 views41 Folien
Introduction to NumPy (PyData SV 2013) von
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
19.1K views41 Folien
Scientific Computing with Python - NumPy | WeiYuan von
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanWei-Yuan Chang
516 views77 Folien

Similar a Essential numpy before you start your Machine Learning journey in python.pdf(20)

ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH... von DineshThallapelly
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
Introduction to NumPy von Huy Nguyen
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
Huy Nguyen774 views
Introduction to NumPy (PyData SV 2013) von PyData
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData19.1K views
Scientific Computing with Python - NumPy | WeiYuan von Wei-Yuan Chang
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuan
Wei-Yuan Chang516 views
Data Manipulation with Numpy and Pandas in PythonStarting with N von OllieShoresna
Data Manipulation with Numpy and Pandas in PythonStarting with NData Manipulation with Numpy and Pandas in PythonStarting with N
Data Manipulation with Numpy and Pandas in PythonStarting with N
OllieShoresna5 views
Numpy python cheat_sheet von Zahid Hasan
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
Zahid Hasan389 views
Arrays in python von Lifna C.S
Arrays in pythonArrays in python
Arrays in python
Lifna C.S1.5K views
Python - Numpy/Pandas/Matplot Machine Learning Libraries von Andrew Ferlitsch
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch3.5K views

Último

apple.pptx von
apple.pptxapple.pptx
apple.pptxhoneybeeqwe
6 views15 Folien
Employees attrition von
Employees attritionEmployees attrition
Employees attritionMaryAlejandraDiaz
5 views5 Folien
Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language... von
Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language...Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language...
Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language...patiladiti752
6 views15 Folien
Inawisdom Quick Sight von
Inawisdom Quick SightInawisdom Quick Sight
Inawisdom Quick SightPhilipBasford
7 views27 Folien
Custom Tag Manager Templates von
Custom Tag Manager TemplatesCustom Tag Manager Templates
Custom Tag Manager TemplatesMarkus Baersch
29 views17 Folien
Best Home Security Systems.pptx von
Best Home Security Systems.pptxBest Home Security Systems.pptx
Best Home Security Systems.pptxmogalang
9 views16 Folien

Último(20)

Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language... von patiladiti752
Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language...Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language...
Enhancing Financial Sentiment Analysis via Retrieval Augmented Large Language...
patiladiti7526 views
Best Home Security Systems.pptx von mogalang
Best Home Security Systems.pptxBest Home Security Systems.pptx
Best Home Security Systems.pptx
mogalang9 views
[DSC Europe 23][AI:CSI] Aleksa Stojanovic - Applying AI for Threat Detection ... von DataScienceConferenc1
[DSC Europe 23][AI:CSI] Aleksa Stojanovic - Applying AI for Threat Detection ...[DSC Europe 23][AI:CSI] Aleksa Stojanovic - Applying AI for Threat Detection ...
[DSC Europe 23][AI:CSI] Aleksa Stojanovic - Applying AI for Threat Detection ...
[DSC Europe 23][Cryptica] Martin_Summer_Digital_central_bank_money_Ideas_init... von DataScienceConferenc1
[DSC Europe 23][Cryptica] Martin_Summer_Digital_central_bank_money_Ideas_init...[DSC Europe 23][Cryptica] Martin_Summer_Digital_central_bank_money_Ideas_init...
[DSC Europe 23][Cryptica] Martin_Summer_Digital_central_bank_money_Ideas_init...
6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf von 10urkyr34
6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf
6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf
10urkyr347 views
Listed Instruments Survey 2022.pptx von secretariat4
Listed Instruments Survey  2022.pptxListed Instruments Survey  2022.pptx
Listed Instruments Survey 2022.pptx
secretariat493 views
Ukraine Infographic_22NOV2023_v2.pdf von AnastosiyaGurin
Ukraine Infographic_22NOV2023_v2.pdfUkraine Infographic_22NOV2023_v2.pdf
Ukraine Infographic_22NOV2023_v2.pdf
AnastosiyaGurin1.4K views
PRIVACY AWRE PERSONAL DATA STORAGE von antony420421
PRIVACY AWRE PERSONAL DATA STORAGEPRIVACY AWRE PERSONAL DATA STORAGE
PRIVACY AWRE PERSONAL DATA STORAGE
antony4204217 views
CRM stick or twist.pptx von info828217
CRM stick or twist.pptxCRM stick or twist.pptx
CRM stick or twist.pptx
info82821711 views
DGST Methodology Presentation.pdf von maddierlegum
DGST Methodology Presentation.pdfDGST Methodology Presentation.pdf
DGST Methodology Presentation.pdf
maddierlegum7 views
Data Journeys Hard Talk workshop final.pptx von info828217
Data Journeys Hard Talk workshop final.pptxData Journeys Hard Talk workshop final.pptx
Data Journeys Hard Talk workshop final.pptx
info82821711 views
Games, Queries, and Argumentation Frameworks: Time for a Family Reunion von Bertram Ludäscher
Games, Queries, and Argumentation Frameworks: Time for a Family ReunionGames, Queries, and Argumentation Frameworks: Time for a Family Reunion
Games, Queries, and Argumentation Frameworks: Time for a Family Reunion
[DSC Europe 23][DigiHealth] Muthu Ramachandran AI and Blockchain Framework fo... von DataScienceConferenc1
[DSC Europe 23][DigiHealth] Muthu Ramachandran AI and Blockchain Framework fo...[DSC Europe 23][DigiHealth] Muthu Ramachandran AI and Blockchain Framework fo...
[DSC Europe 23][DigiHealth] Muthu Ramachandran AI and Blockchain Framework fo...
Product Research sample.pdf von AllenSingson
Product Research sample.pdfProduct Research sample.pdf
Product Research sample.pdf
AllenSingson33 views

Essential numpy before you start your Machine Learning journey in python.pdf

  • 1. Essential numpy before you start your Machine Learning journey in python Linkedin: https://www.linkedin.com/in/smrati/ Twitter: https://twitter.com/SmratiKatiyar importing numpy Creating a numpy array NumPy offers various ways to create arrays. Here are some of the different methods for creating NumPy arrays: 1. Using Lists or Tuples: You can create a NumPy array from a Python list or tuple. 2. Using NumPy Functions: NumPy provides functions like np.zeros() , np.ones() , np.empty() , and np.full() to create arrays filled with specific values. import numpy as np import numpy as np # Create an array from a list arr_from_list = np.array([1, 2, 3, 4, 5]) # Create an array from a tuple arr_from_tuple = np.array((1, 2, 3, 4, 5)) import numpy as np # Create an array of zeros zeros_array = np.zeros(5) # Create an array of ones ones_array = np.ones(5) # Create an empty array (initialized with random values) empty_array = np.empty(5) # Create an array filled with a specific value
  • 2. 3. Using Ranges: You can create arrays with regularly spaced values using functions like np.arange() and np.linspace() . 4. Using Random Data: NumPy provides functions in the np.random module to generate arrays with random data. 5. Using Identity Matrix: You can create a 2D identity matrix using np.eye() . 6. Using Existing Data: You can create a NumPy array from existing data, such as a Python list or another NumPy array. filled_array = np.full(5, 7) # Creates an array of 5 elements, each with the value 7 import numpy as np # Create an array with values from 0 to 4 (exclusive) range_array = np.arange(0, 5) # Create an array of 5 equally spaced values between 0 and 1 (inclusive) linspace_array = np.linspace(0, 1, 5) import numpy as np # Create an array of random values between 0 and 1 random_array = np.random.rand(5) # Create a 2D array of random integers between 1 and 100 random_int_array = np.random.randint(1, 101, size=(3, 3)) import numpy as np # Create a 3x3 identity matrix identity_matrix = np.eye(3) import numpy as np # Create an array from an existing list existing_list = [1, 2, 3] array_from_list = np.array(existing_list) # Create an array from an existing NumPy array
  • 3. These are some of the common ways to create NumPy arrays. Depending on your specific needs and data, you can choose the most appropriate method for creating your array. Element wise addition , subtraction , multiplication and division Output: Numpy array and scalar interaction to each element (known as broadcasting) Output: existing_array = np.array([4, 5, 6]) array_from_existing = np.array(existing_array) import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) plus = x + y minus = x - y mut = x * y div = x / y mod = y % x print(plus) print(minus) print(mut) print(div) print(mod) [5 7 9] [-3 -3 -3] [ 4 10 18] [0.25 0.4 0.5 ] [0 1 0] import numpy as np x = np.array([1, 2, 3]) print(x + 2) [3 4 5]
  • 4. Checking shape and datatype of numpy array Output: Matrix multiplication using numpy array Output: vector, matrix and tensor In NumPy, you can represent vectors, matrices, and tensors using arrays. Here's an explanation of the differences between these three concepts with NumPy examples: 1. Vector: A vector is a one-dimensional array that represents a list of numbers or values. It has a single row (or column) of elements. In NumPy, you can create a vector using a 1D array. import numpy as np x = np.array([1, 2, 3]) y = np.array([1.7, 2, 3]) print(x.shape) print(x.dtype) print(y.dtype) (3,) int64 float64 import numpy as np x = np.array([[1, 2, 3], [1, 2, 3]]) y = np.array([[1, 2], [1, 2], [1, 2]]) print(x.shape) print(y.shape) print(np.matmul(x, y)) (2, 3) (3, 2) [[ 6 12] [ 6 12]] import numpy as np
  • 5. 2. Matrix: A matrix is a two-dimensional array where each element is identified by two indices (rows and columns). In NumPy, you can create a matrix using a 2D array. 3. Tensor: A tensor is a multi-dimensional array with more than two dimensions. It can have three or more dimensions. In NumPy, you can create tensors using arrays with more than two dimensions. In the examples above: vector is a 1D NumPy array with shape (5,) . matrix is a 2D NumPy array with shape (3, 3) . tensor is a 3D NumPy array with shape (2, 2, 2) . To summarize, the key difference between these concepts is their dimensionality: Vectors are 1D arrays. Matrices are 2D arrays. Tensors are multi-dimensional arrays with three or more dimensions. Broadcasting Broadcasting in NumPy is a powerful feature that allows you to perform operations on arrays of different shapes, making them compatible for element-wise operations without explicitly creating new arrays to match their shapes. In simple terms, broadcasting helps NumPy "stretch" smaller arrays to make them compatible with larger arrays, so you can perform operations on them efficiently. Here's a simplified explanation of broadcasting with an example: Suppose you have two NumPy arrays: # Creating a vector vector = np.array([1, 2, 3, 4, 5]) import numpy as np # Creating a matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) import numpy as np # Creating a tensor (3D example) tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
  • 6. 1. Array A with shape (3, 3) : 2. Array B with shape (1, 3) : Now, you want to add these two arrays together element-wise. Normally, you would need arrays with the same shape for element-wise addition, but broadcasting allows you to perform this operation without explicitly copying or reshaping the smaller array. Here's how broadcasting works in this case: 1. NumPy identifies that the dimensions of the arrays are not the same. 2. It checks if the dimensions are compatible for broadcasting by comparing them from the right side (trailing dimensions). 3. In this example, the dimensions are compatible because the size of the last dimension of array B (which is 3) matches the size of the corresponding dimension in array A . 4. NumPy effectively "stretches" or "broadcasts" the smaller array B to match the shape of the larger array A , making it look like this: 5. Now, NumPy can perform element-wise addition between the two arrays: So, broadcasting allows you to perform operations between arrays of different shapes by automatically making them compatible, without the need for manual reshaping or copying of data. This makes your code more concise and efficient when working with NumPy arrays. Access element in numpy arrays Accessing elements in NumPy arrays is straightforward and involves specifying the indices of the elements you want to retrieve. NumPy supports several ways to access elements, including basic A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [10, 20, 30] B = [[10, 20, 30], [10, 20, 30], [10, 20, 30]] Result = A + B = [[1+10, 2+20, 3+30], [4+10, 5+20, 6+30], [7+10, 8+20, 9+30]] = [[11, 22, 33], [14, 25, 36], [17, 28, 39]]
  • 7. indexing, slicing, and fancy indexing. Let's go through each of these methods: 1. Basic Indexing: To access a single element in a NumPy array, you can use square brackets and specify the row and column (or just a single index for 1D arrays). 2. Slicing: You can access multiple elements or subarrays using slicing. Slicing allows you to specify a range of indices. 3. Boolean Indexing (Fancy Indexing): You can use boolean arrays to filter elements based on a condition. 4. Integer Array Indexing (Fancy Indexing): You can use integer arrays to access elements by specifying the indices explicitly. import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Access a single element element = arr[0, 1] # Accesses the element at row 0, column 1 (value: 2) import numpy as np arr = np.array([0, 1, 2, 3, 4, 5]) # Access a slice of elements subarray = arr[2:5] # Retrieves elements from index 2 to 4 (values: [2, 3, 4]) # Access a subarray of a 2D array subarray_2d = arr[1:3, 1:3] # Retrieves a 2x2 subarray from the original 2D array import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Create a boolean mask mask = (arr % 2 == 0) # Use the mask to access elements that meet the condition even_numbers = arr[mask] # Retrieves elements [2, 4]
  • 8. 5. Negative Indexing: You can use negative indices to access elements from the end of an array. Remember that indexing in NumPy is zero-based, meaning the first element is accessed using index 0. Additionally, indexing and slicing can be applied to both 1D and multidimensional (2D, 3D, etc.) arrays, with different syntax for each dimension. import numpy as np arr = np.array([10, 20, 30, 40, 50]) # Create an array of indices indices = np.array([1, 3]) # Use the indices to access specific elements selected_elements = arr[indices] # Retrieves elements [20, 40] import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Access the last element using negative indexing last_element = arr[-1] # Retrieves the last element (value: 5)