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

Smrati Kumar Katiyar
Smrati Kumar KatiyarWrite codes at askme.com à 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)

Recommandé

NUMPY-2.pptx par
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptxMahendraVusa
30 vues91 diapositives
NumPy.pptx par
NumPy.pptxNumPy.pptx
NumPy.pptxEN1036VivekSingh
150 vues44 diapositives
arraycreation.pptx par
arraycreation.pptxarraycreation.pptx
arraycreation.pptxsathya930629
8 vues13 diapositives
CAP776Numpy (2).ppt par
CAP776Numpy (2).pptCAP776Numpy (2).ppt
CAP776Numpy (2).pptChhaviCoachingCenter
4 vues88 diapositives
CAP776Numpy.ppt par
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.pptkdr52121
16 vues88 diapositives
Numpy - Array.pdf par
Numpy - Array.pdfNumpy - Array.pdf
Numpy - Array.pdfAnkitaArjunDevkate
122 vues21 diapositives

Contenu connexe

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

NUMPY par
NUMPY NUMPY
NUMPY SharmilaChidaravalli
6.2K vues24 diapositives
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH... par
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...DineshThallapelly
5 vues18 diapositives
CE344L-200365-Lab2.pdf par
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
5 vues1 diapositive
Introduction to NumPy par
Introduction to NumPyIntroduction to NumPy
Introduction to NumPyHuy Nguyen
769 vues41 diapositives
Introduction to NumPy (PyData SV 2013) par
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
19.1K vues41 diapositives
Scientific Computing with Python - NumPy | WeiYuan par
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanWei-Yuan Chang
516 vues77 diapositives

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

ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH... par DineshThallapelly
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
Introduction to NumPy par Huy Nguyen
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
Huy Nguyen769 vues
Introduction to NumPy (PyData SV 2013) par PyData
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData19.1K vues
Scientific Computing with Python - NumPy | WeiYuan par Wei-Yuan Chang
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuan
Wei-Yuan Chang516 vues
Data Manipulation with Numpy and Pandas in PythonStarting with N par 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 vues
Numpy python cheat_sheet par Zahid Hasan
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
Zahid Hasan386 vues
Arrays in python par Lifna C.S
Arrays in pythonArrays in python
Arrays in python
Lifna C.S1.5K vues
Python - Numpy/Pandas/Matplot Machine Learning Libraries par 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 vues

Dernier

[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx par
[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx
[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptxDataScienceConferenc1
5 vues12 diapositives
Supercharging your Data with Azure AI Search and Azure OpenAI par
Supercharging your Data with Azure AI Search and Azure OpenAISupercharging your Data with Azure AI Search and Azure OpenAI
Supercharging your Data with Azure AI Search and Azure OpenAIPeter Gallagher
37 vues32 diapositives
Data structure and algorithm. par
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm. Abdul salam
19 vues24 diapositives
Advanced_Recommendation_Systems_Presentation.pptx par
Advanced_Recommendation_Systems_Presentation.pptxAdvanced_Recommendation_Systems_Presentation.pptx
Advanced_Recommendation_Systems_Presentation.pptxneeharikasingh29
5 vues9 diapositives
RIO GRANDE SUPPLY COMPANY INC, JAYSON.docx par
RIO GRANDE SUPPLY COMPANY INC, JAYSON.docxRIO GRANDE SUPPLY COMPANY INC, JAYSON.docx
RIO GRANDE SUPPLY COMPANY INC, JAYSON.docxJaysonGarabilesEspej
6 vues3 diapositives
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdf par
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdfVikas 500 BIG DATA TECHNOLOGIES LAB.pdf
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdfvikas12611618
8 vues30 diapositives

Dernier(20)

[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx par DataScienceConferenc1
[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx
[DSC Europe 23] Zsolt Feleki - Machine Translation should we trust it.pptx
Supercharging your Data with Azure AI Search and Azure OpenAI par Peter Gallagher
Supercharging your Data with Azure AI Search and Azure OpenAISupercharging your Data with Azure AI Search and Azure OpenAI
Supercharging your Data with Azure AI Search and Azure OpenAI
Peter Gallagher37 vues
Data structure and algorithm. par Abdul salam
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm.
Abdul salam 19 vues
Advanced_Recommendation_Systems_Presentation.pptx par neeharikasingh29
Advanced_Recommendation_Systems_Presentation.pptxAdvanced_Recommendation_Systems_Presentation.pptx
Advanced_Recommendation_Systems_Presentation.pptx
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdf par vikas12611618
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdfVikas 500 BIG DATA TECHNOLOGIES LAB.pdf
Vikas 500 BIG DATA TECHNOLOGIES LAB.pdf
vikas126116188 vues
Cross-network in Google Analytics 4.pdf par GA4 Tutorials
Cross-network in Google Analytics 4.pdfCross-network in Google Analytics 4.pdf
Cross-network in Google Analytics 4.pdf
GA4 Tutorials6 vues
Organic Shopping in Google Analytics 4.pdf par GA4 Tutorials
Organic Shopping in Google Analytics 4.pdfOrganic Shopping in Google Analytics 4.pdf
Organic Shopping in Google Analytics 4.pdf
GA4 Tutorials11 vues
UNEP FI CRS Climate Risk Results.pptx par pekka28
UNEP FI CRS Climate Risk Results.pptxUNEP FI CRS Climate Risk Results.pptx
UNEP FI CRS Climate Risk Results.pptx
pekka2811 vues
Short Story Assignment by Kelly Nguyen par kellynguyen01
Short Story Assignment by Kelly NguyenShort Story Assignment by Kelly Nguyen
Short Story Assignment by Kelly Nguyen
kellynguyen0119 vues
Understanding Hallucinations in LLMs - 2023 09 29.pptx par Greg Makowski
Understanding Hallucinations in LLMs - 2023 09 29.pptxUnderstanding Hallucinations in LLMs - 2023 09 29.pptx
Understanding Hallucinations in LLMs - 2023 09 29.pptx
Greg Makowski17 vues
Chapter 3b- Process Communication (1) (1)(1) (1).pptx par ayeshabaig2004
Chapter 3b- Process Communication (1) (1)(1) (1).pptxChapter 3b- Process Communication (1) (1)(1) (1).pptx
Chapter 3b- Process Communication (1) (1)(1) (1).pptx
RuleBookForTheFairDataEconomy.pptx par noraelstela1
RuleBookForTheFairDataEconomy.pptxRuleBookForTheFairDataEconomy.pptx
RuleBookForTheFairDataEconomy.pptx
noraelstela167 vues
[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation par DataScienceConferenc1
[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation
[DSC Europe 23] Spela Poklukar & Tea Brasanac - Retrieval Augmented Generation

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)