SlideShare a Scribd company logo
Numpy ndarrays
One of the fundamental components of NumPy is the ndarray (short for
“n-dimensional array”). The ndarray is a versatile data structure that enables
you to work with homogeneous, multi-dimensional data. In this guide, we’ll
dive deep into understanding ndarray, its structure, attributes, and
operations.
Introduction to ndarrays
An ndarray is a multi-dimensional, homogeneous array of elements, all of the
same data type. It provides a convenient way to store and manipulate large
datasets, such as images, audio, and scientific data. ndarrays are the lynchpin
of many scientific and data analysis libraries in Python.
Creating ndarrays
Follow TechVidvan on Google & Stay updated with latest
technology trends
Using numpy.array()
The numpy.array() function allows you to create an ndarray from an existing
list or iterable.
import numpy as np
data_list = [1, 2, 3, 4, 5]
arr = np.array(data_list)
Using numpy.zeros() and numpy.ones()
You can create arrays filled with zeros or ones using these functions.
zeros_arr = np.zeros((3, 4)) # Creates a 3x4 array of zeros
ones_arr = np.ones((2, 2)) # Creates a 2x2 array of ones
Using numpy.arange() and numpy.linspace()
numpy.arange() generates an array with evenly spaced values within a
specified range, while numpy.linspace() generates an array with a specified
number of evenly spaced values between a start and end.
range_arr = np.arange(0, 10, 2) # Array from 0 to 10 with
step 2
linspace_arr = np.linspace(0, 1, 5) # Array of 5 values from
0 to 1
Parameters of the ndarray Class
a. shape
The shape parameter is a tuple of integers that defines the dimensions of the
created array. It specifies the size of the array along each axis, making it
possible to create arrays of different shapes, from one-dimensional to
multi-dimensional arrays.
b. dtype (data type)
The dtype parameter specifies the data type of the elements within the array.
It can be any object that can be interpreted as a NumPy data type. This allows
you to control the precision and characteristics of the data stored in the array,
whether it’s integers, floating-point numbers, or other custom data types.
c. buffer
The buffer parameter is an optional object that exposes the buffer interface. It
can be used to fill the array with data from an existing buffer. This is useful
when you want to create an ndarray that shares data with another object, such
as a Python bytes object or another ndarray.
d. offset
The offset parameter is an integer that specifies the offset of the array data
within the buffer (if the buffer parameter is provided). It allows you to start
filling the array from a particular position within the buffer, which can be
useful for creating views or sub-arrays.
e. Strides
The strides parameter is an optional tuple of integers that defines the strides
of data in memory. Strides determine the number of bytes to move in memory
to access the next element along each axis. This parameter can be used to
create arrays with non-contiguous data layouts, enabling efficient operations
on sub-arrays or views.
f. order
The order parameter specifies the memory layout order of the array. It can
take two values: ‘C’ for row-major (C-style) order and ‘F’ for column-major
(Fortran-style) order. The memory layout affects how the elements are stored
in memory, and it can influence the efficiency of accessing elements in
different patterns.
Attributes of the ndarray Class
a. T (Transpose)
The T attribute returns a view of the transposed array. This operation flips the
dimensions of the array, effectively swapping rows and columns. It is
especially useful for linear algebra operations and matrix manipulations.
b. data (Buffer)
The data attribute is a Python buffer object that points to the start of the
array’s data. It provides a direct interface to the underlying memory of the
array, allowing for seamless interaction with other libraries or Python’s
memory buffers.
c. dtype (Data Type)
The dtype attribute returns a dtype object that describes the data type of the
array’s elements. It provides information about the precision, size, and
interpretation of the data, whether it’s integers, floating-point numbers, or
custom-defined data types.
d. flags (Memory Layout Information)
The flags attribute returns a dictionary containing information about the
memory layout of the array. It includes details like whether the array is
C-contiguous, Fortran-contiguous, or read-only. This information can be
crucial for optimizing array operations.
e. flat (1-D Iterator)
The flat attribute returns a 1-D iterator over the array. This iterator allows you
to efficiently traverse all elements in the array, regardless of their shape. It’s
particularly useful when you want to apply an operation to each element in the
array without the need for explicit loops.
f. imag and real (Imaginary and Real Parts)
The image and real attributes return separate ndarrays representing the
imaginary and real parts of the original array, respectively. This is particularly
relevant for complex numbers, allowing you to manipulate the real and
imaginary components individually.
g. size (Number of Elements)
The size attribute returns an integer indicating the total number of elements in
the array. It’s a convenient way to quickly determine the array’s overall
capacity.
h. item size (Element Size in Bytes)
The item size attribute returns an integer representing the size of a single
array element in bytes. This is essential for calculating the total memory
consumption of the array.
i. nbytes (Total Bytes Consumed)
The nbytes attribute is an integer indicating the total number of bytes
consumed by all elements in the array. It’s a comprehensive measure of the
memory usage of the array.
j. ndim (Number of Dimensions)
The ndim attribute returns an integer indicating the number of dimensions in
the array. It defines the array’s rank or order.
k. shape (Array Dimensions)
The shape attribute returns a tuple of integers representing the dimensions of
the array. It defines the size of the array along each axis.
l. strides (Byte Steps)
The strides attribute returns a tuple of integers indicating the number of bytes
to step in each dimension when traversing the array. This information is
crucial for understanding how the array’s data is laid out in memory.
m. ctypes (Interaction with ctypes)
The ctypes attribute provides an object that simplifies the interaction of the
array with the ctypes module, which is useful for interoperability with
low-level languages like C.
n. base (Base Array)
The base attribute returns the base array if the memory is derived from some
other object. This is particularly relevant when working with views or arrays
that share memory with other arrays.
Indexing and Slicing
You can access elements within an ndarray using indexing and slicing.
Advertisement
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1]) # Output: 2 (element at row 0, column 1)
print(arr[:, 1:3]) # Output: [[2, 3], [5, 6]] (slicing columns
1 and 2)
Array Operations
Element-wise Operations
ndarrays support element-wise operations like addition, subtraction,
multiplication, and division.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = arr1 + arr2 # Element-wise addition
print(result)
Output:
[5 7 9]
Broadcasting
Broadcasting allows arrays with different shapes to be combined in
operations.
arr = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 2
result = arr + scalar # Broadcasting scalar to all elements
print(result)
Output:
[[3 4 5]
[6 7 8]]
Reshaping and Transposing
You can reshape and transpose ndarrays to change their dimensions and
orientations.
arr = np.array([[1, 2, 3], [4, 5, 6]])
reshaped_arr = arr.reshape((3, 2)) # Reshaping to 3x2
transposed_arr = arr.T # Transposing the array
print("Original Array:")
print(arr)
print("nReshaped Array (3x2):")
print(reshaped_arr)
print("nTransposed Array:")
print(transposed_arr)
Output:
Original Array:
[[1 2 3]
[4 5 6]]
Reshaped Array (3×2):
[[1 2]
[3 4]
[5 6]]
Transposed Array:
[[1 4]
[2 5]
[3 6]]
Aggregation and Statistical Functions
NumPy provides numerous functions for calculating aggregates and statistics.
arr = np.array([1, 2, 3, 4, 5])
mean = np.mean(arr)
median = np.median(arr)
std_dev = np.std(arr)
print("Array:", arr)
print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std_dev)
Output:
Array: [1 2 3 4 5]
Mean: 3.0
Median: 3.0
Standard Deviation: 1.4142135623730951
Boolean Indexing and Fancy Indexing
Boolean indexing allows you to select elements
based on conditions.
arr = np.array([10, 20, 30, 40, 50])
mask = arr > 30
result = arr[mask]
Output: [40, 50]
Fancy indexing involves selecting elements using
integer arrays.
arr = np.array([1, 2, 3, 4, 5])
indices = np.array([1, 3])
result = arr[indices]
Output: [2, 4]
Conclusion
In this tutorial, we’ve explored the world of ndarrays in NumPy. We’ve
ventured into creating ndarrays, understanding their attributes, performing
various operations, and even touching on advanced indexing techniques. The
ndarray’s versatility and efficiency make it an essential tool for numerical
computations and data analysis in Python. With the knowledge gained here,
you’re well-equipped to start harnessing the power of NumPy ndarrays for
your own projects. Happy coding!

More Related Content

Similar to Numpy ndarrays.pdf

python-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxpython-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptx
Akashgupta517936
 
Arrays
ArraysArrays
Arrays
ViniVini48
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
SivaSankar Gorantla
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Arrays Introduction.pptx
Arrays Introduction.pptxArrays Introduction.pptx
Arrays Introduction.pptx
AtheenaNugent1
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
DrJasmineBeulahG
 
Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r
Ashwini Mathur
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
Rai University
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer Graphics
Prabu U
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
Rai University
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
Rai University
 
Svm Presentation
Svm PresentationSvm Presentation
Svm Presentationshahparin
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
ambikavenkatesh2
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
 
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.pptDATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
yarotos643
 
The actual illustration of values is decided by the machine design (.pdf
The actual illustration of values is decided by the machine design (.pdfThe actual illustration of values is decided by the machine design (.pdf
The actual illustration of values is decided by the machine design (.pdf
anyacarpets
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
swathirajstar
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
Abbott
 

Similar to Numpy ndarrays.pdf (20)

python-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptxpython-numpyandpandas-170922144956 (1).pptx
python-numpyandpandas-170922144956 (1).pptx
 
Arrays
ArraysArrays
Arrays
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Arrays Introduction.pptx
Arrays Introduction.pptxArrays Introduction.pptx
Arrays Introduction.pptx
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
arrays.docx
arrays.docxarrays.docx
arrays.docx
 
Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r Summerization notes for descriptive statistics using r
Summerization notes for descriptive statistics using r
 
Bsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structureBsc cs ii dfs u-1 introduction to data structure
Bsc cs ii dfs u-1 introduction to data structure
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer Graphics
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Svm Presentation
Svm PresentationSvm Presentation
Svm Presentation
 
data structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysoredata structures using C 2 sem BCA univeristy of mysore
data structures using C 2 sem BCA univeristy of mysore
 
DS_PPT.pptx
DS_PPT.pptxDS_PPT.pptx
DS_PPT.pptx
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.pptDATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
 
The actual illustration of values is decided by the machine design (.pdf
The actual illustration of values is decided by the machine design (.pdfThe actual illustration of values is decided by the machine design (.pdf
The actual illustration of values is decided by the machine design (.pdf
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
 
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
 

More from SudhanshiBakre1

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
SudhanshiBakre1
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
SudhanshiBakre1
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
SudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
SudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
SudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
SudhanshiBakre1
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
SudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
SudhanshiBakre1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
SudhanshiBakre1
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
SudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
SudhanshiBakre1
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
SudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
SudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
SudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
SudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

Numpy ndarrays.pdf

  • 1. Numpy ndarrays One of the fundamental components of NumPy is the ndarray (short for “n-dimensional array”). The ndarray is a versatile data structure that enables you to work with homogeneous, multi-dimensional data. In this guide, we’ll dive deep into understanding ndarray, its structure, attributes, and operations. Introduction to ndarrays An ndarray is a multi-dimensional, homogeneous array of elements, all of the same data type. It provides a convenient way to store and manipulate large datasets, such as images, audio, and scientific data. ndarrays are the lynchpin of many scientific and data analysis libraries in Python. Creating ndarrays Follow TechVidvan on Google & Stay updated with latest technology trends Using numpy.array() The numpy.array() function allows you to create an ndarray from an existing list or iterable. import numpy as np data_list = [1, 2, 3, 4, 5] arr = np.array(data_list)
  • 2. Using numpy.zeros() and numpy.ones() You can create arrays filled with zeros or ones using these functions. zeros_arr = np.zeros((3, 4)) # Creates a 3x4 array of zeros ones_arr = np.ones((2, 2)) # Creates a 2x2 array of ones Using numpy.arange() and numpy.linspace() numpy.arange() generates an array with evenly spaced values within a specified range, while numpy.linspace() generates an array with a specified number of evenly spaced values between a start and end. range_arr = np.arange(0, 10, 2) # Array from 0 to 10 with step 2 linspace_arr = np.linspace(0, 1, 5) # Array of 5 values from 0 to 1 Parameters of the ndarray Class a. shape The shape parameter is a tuple of integers that defines the dimensions of the created array. It specifies the size of the array along each axis, making it possible to create arrays of different shapes, from one-dimensional to multi-dimensional arrays.
  • 3. b. dtype (data type) The dtype parameter specifies the data type of the elements within the array. It can be any object that can be interpreted as a NumPy data type. This allows you to control the precision and characteristics of the data stored in the array, whether it’s integers, floating-point numbers, or other custom data types. c. buffer The buffer parameter is an optional object that exposes the buffer interface. It can be used to fill the array with data from an existing buffer. This is useful when you want to create an ndarray that shares data with another object, such as a Python bytes object or another ndarray. d. offset The offset parameter is an integer that specifies the offset of the array data within the buffer (if the buffer parameter is provided). It allows you to start filling the array from a particular position within the buffer, which can be useful for creating views or sub-arrays. e. Strides The strides parameter is an optional tuple of integers that defines the strides of data in memory. Strides determine the number of bytes to move in memory to access the next element along each axis. This parameter can be used to create arrays with non-contiguous data layouts, enabling efficient operations on sub-arrays or views. f. order
  • 4. The order parameter specifies the memory layout order of the array. It can take two values: ‘C’ for row-major (C-style) order and ‘F’ for column-major (Fortran-style) order. The memory layout affects how the elements are stored in memory, and it can influence the efficiency of accessing elements in different patterns. Attributes of the ndarray Class a. T (Transpose) The T attribute returns a view of the transposed array. This operation flips the dimensions of the array, effectively swapping rows and columns. It is especially useful for linear algebra operations and matrix manipulations. b. data (Buffer) The data attribute is a Python buffer object that points to the start of the array’s data. It provides a direct interface to the underlying memory of the array, allowing for seamless interaction with other libraries or Python’s memory buffers. c. dtype (Data Type) The dtype attribute returns a dtype object that describes the data type of the array’s elements. It provides information about the precision, size, and interpretation of the data, whether it’s integers, floating-point numbers, or custom-defined data types. d. flags (Memory Layout Information)
  • 5. The flags attribute returns a dictionary containing information about the memory layout of the array. It includes details like whether the array is C-contiguous, Fortran-contiguous, or read-only. This information can be crucial for optimizing array operations. e. flat (1-D Iterator) The flat attribute returns a 1-D iterator over the array. This iterator allows you to efficiently traverse all elements in the array, regardless of their shape. It’s particularly useful when you want to apply an operation to each element in the array without the need for explicit loops. f. imag and real (Imaginary and Real Parts) The image and real attributes return separate ndarrays representing the imaginary and real parts of the original array, respectively. This is particularly relevant for complex numbers, allowing you to manipulate the real and imaginary components individually. g. size (Number of Elements) The size attribute returns an integer indicating the total number of elements in the array. It’s a convenient way to quickly determine the array’s overall capacity. h. item size (Element Size in Bytes)
  • 6. The item size attribute returns an integer representing the size of a single array element in bytes. This is essential for calculating the total memory consumption of the array. i. nbytes (Total Bytes Consumed) The nbytes attribute is an integer indicating the total number of bytes consumed by all elements in the array. It’s a comprehensive measure of the memory usage of the array. j. ndim (Number of Dimensions) The ndim attribute returns an integer indicating the number of dimensions in the array. It defines the array’s rank or order. k. shape (Array Dimensions) The shape attribute returns a tuple of integers representing the dimensions of the array. It defines the size of the array along each axis. l. strides (Byte Steps) The strides attribute returns a tuple of integers indicating the number of bytes to step in each dimension when traversing the array. This information is crucial for understanding how the array’s data is laid out in memory. m. ctypes (Interaction with ctypes)
  • 7. The ctypes attribute provides an object that simplifies the interaction of the array with the ctypes module, which is useful for interoperability with low-level languages like C. n. base (Base Array) The base attribute returns the base array if the memory is derived from some other object. This is particularly relevant when working with views or arrays that share memory with other arrays. Indexing and Slicing You can access elements within an ndarray using indexing and slicing. Advertisement arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr[0, 1]) # Output: 2 (element at row 0, column 1) print(arr[:, 1:3]) # Output: [[2, 3], [5, 6]] (slicing columns 1 and 2) Array Operations Element-wise Operations ndarrays support element-wise operations like addition, subtraction, multiplication, and division. arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) result = arr1 + arr2 # Element-wise addition print(result)
  • 8. Output: [5 7 9] Broadcasting Broadcasting allows arrays with different shapes to be combined in operations. arr = np.array([[1, 2, 3], [4, 5, 6]]) scalar = 2 result = arr + scalar # Broadcasting scalar to all elements print(result) Output: [[3 4 5] [6 7 8]] Reshaping and Transposing You can reshape and transpose ndarrays to change their dimensions and orientations. arr = np.array([[1, 2, 3], [4, 5, 6]]) reshaped_arr = arr.reshape((3, 2)) # Reshaping to 3x2 transposed_arr = arr.T # Transposing the array print("Original Array:") print(arr) print("nReshaped Array (3x2):") print(reshaped_arr)
  • 9. print("nTransposed Array:") print(transposed_arr) Output: Original Array: [[1 2 3] [4 5 6]] Reshaped Array (3×2): [[1 2] [3 4] [5 6]] Transposed Array: [[1 4] [2 5] [3 6]] Aggregation and Statistical Functions NumPy provides numerous functions for calculating aggregates and statistics. arr = np.array([1, 2, 3, 4, 5]) mean = np.mean(arr) median = np.median(arr) std_dev = np.std(arr) print("Array:", arr) print("Mean:", mean) print("Median:", median)
  • 10. print("Standard Deviation:", std_dev) Output: Array: [1 2 3 4 5] Mean: 3.0 Median: 3.0 Standard Deviation: 1.4142135623730951 Boolean Indexing and Fancy Indexing Boolean indexing allows you to select elements based on conditions. arr = np.array([10, 20, 30, 40, 50]) mask = arr > 30 result = arr[mask] Output: [40, 50] Fancy indexing involves selecting elements using integer arrays. arr = np.array([1, 2, 3, 4, 5]) indices = np.array([1, 3]) result = arr[indices] Output: [2, 4] Conclusion
  • 11. In this tutorial, we’ve explored the world of ndarrays in NumPy. We’ve ventured into creating ndarrays, understanding their attributes, performing various operations, and even touching on advanced indexing techniques. The ndarray’s versatility and efficiency make it an essential tool for numerical computations and data analysis in Python. With the knowledge gained here, you’re well-equipped to start harnessing the power of NumPy ndarrays for your own projects. Happy coding!