SlideShare a Scribd company logo
Introduction toIntroduction to
NumPyNumPy
Bryan Van de VenBryan Van de Ven
What is NumPyWhat is NumPy
NumPy is a Python C extension library for array-oriented computing
Efficient
In-memory
Contiguous (or Strided)
Homogeneous (but types can be algebraic)
NumPy is suited to many applications
Image processing
Signal processing
Linear algebra
A plethora of others
NumPy is the foundation of theNumPy is the foundation of the
python scientific stackpython scientific stack
NumPy EcosystemNumPy Ecosystem
Quick StartQuick Start
In [1]: import numpy as np
In [2]: a = np.array([1,2,3,4,5,6,7,8,9])
In [3]: a
Out[3]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [4]: b = a.reshape((3,3))
In [5]: b
Out[5]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [6]: b * 10 + 4
Out[6]:
array([[14, 24, 34],
[44, 54, 64],
[74, 84, 94]])
Array ShapeArray Shape
One dimensional arrays have a 1-tuple forOne dimensional arrays have a 1-tuple for
their shapetheir shape
...Two dimensional arrays have a 2-tuple...Two dimensional arrays have a 2-tuple
...And so on...And so on
Array Element Type (dtype)Array Element Type (dtype)
NumPy arrays comprise elements of a single data type
The type object is accessible through the .dtype attribute
Here are a few of the most important attributes of dtype objects
dtype.byteorder — big or little endian
dtype.itemsize — element size of this dtype
dtype.name — a name for this dtype object
dtype.type — type object used to create scalars
There are many others...
Array dtypes are usually inferred automatically
But can also be specified explicitly
In [16]: a = np.array([1,2,3])
In [17]: a.dtype
Out[17]: dtype('int64')
In [18]: b = np.array([1,2,3,4.567])
In [19]: b.dtype
Out[19]: dtype('float64')
In [20]: a = np.array([1,2,3], dtype=np.float32)
In [21]: a.dtype
Out[21]: dtype('int64')
In [22]: a
Out[22]: array([ 1., 2., 3.], dtype=float32)
NumPy Builtin dtype HierarchyNumPy Builtin dtype Hierarchy
np.datetime64 is a new addition in NumPy 1.7
Array CreationArray Creation
Explicitly from a list of values
As a range of values
By specifying the number of elements
In [2]: np.array([1,2,3,4])
Out[2]: array([1, 2, 3, 4])
In [3]: np.arange(10)
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [4]: np.linspace(0, 1, 5)
Out[4]: array([ 0. , 0.25, 0.5 , 0.75, 1. ])
Zero-initialized
One-initialized
Uninitialized
In [4]: np.zeros((2,2))
Out[4]:
array([[ 0., 0.],
[ 0., 0.]])
In [5]: np.ones((1,5))
Out[5]: array([[ 1., 1., 1., 1., 1.]])
In [4]: np.empty((1,3))
Out[4]: array([[ 2.12716633e-314, 2.12716633e-314, 2.15203762e-314]])
Constant diagonal value
Multiple diagonal values
In [6]: np.eye(3)
Out[6]:
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
In [7]: np.diag([1,2,3,4])
Out[7]:
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
Array Memory LayoutArray Memory Layout
Indexing and SlicingIndexing and Slicing
Introduction to NumPy (PyData SV 2013)
NumPy array indices can also take an optional stride
Array ViewsArray Views
Simple assigments do not make copies of arrays (same semantics as
Python). Slicing operations do not make copies either; they return views
on the original array.
Array views contain a pointer to the original data, but may have different
shape or stride values. Views always have flags.owndata equal to
False.
In [2]: a = np.arange(10)
In [3]: b = a[3:7]
In [4]: b
Out[4]: array([3, 4, 5, 6])
In [5]: b[:] = 0
In [6]: a
Out[6]: array([0, 1, 3, 0, 0, 0, 0, 7, 8, 9])
In [7]: b.flags.owndata
Out[7]: False
Universal Functions (ufuncs)Universal Functions (ufuncs)
NumPy ufuncs are functions that operate element-wise on one or more
arrays
ufuncs dispatch to optimized C inner-loops based on array dtype
NumPy has many built-in ufuncsNumPy has many built-in ufuncs
comparison: <, <=, ==, !=, >=, >
arithmetic: +, -, *, /, reciprocal, square
exponential: exp, expm1, exp2, log, log10, log1p, log2,
power, sqrt
trigonometric: sin, cos, tan, acsin, arccos, atctan
hyperbolic: sinh, cosh, tanh, acsinh, arccosh, atctanh
bitwise operations: &, |, ~, ^, left_shift, right_shift
logical operations: and, logical_xor, not, or
predicates: isfinite, isinf, isnan, signbit
other: abs, ceil, floor, mod, modf, round, sinc, sign,
trunc
AxisAxis
Array method reductions take an optional axis parameter that specifies
over which axes to reduce
axis=None reduces into a single scalar
In [7]: a.sum
()
Out[7]: 105
axis=None is the default
axis=0 reduces into the zeroth dimension
axis=0 reduces into the first dimension
In [8]: a.sum(axis=0)
Out[8]: array([15, 18, 21, 24,
27])
In [9]: a.sum(axis=1)
Out[9]: array([10, 35, 60])
BroadcastingBroadcasting
A key feature of NumPy is broadcasting, where arrays with different, but
compatible shapes can be used as arguments to ufuncs
In this case an array scalar is broadcast to an array with shape (5, )
A slightly more involved broadcasting example in two dimensions
Here an array of shape (3, 1) is broadcast to an array with shape
(3, 2)
Broadcasting RulesBroadcasting Rules
In order for an operation to broadcast, the size of all the trailing
dimensions for both arrays must either:
be equal OR be one
A (1d array): 3
B (2d array): 2 x 3
Result (2d array): 2 x 3
A (2d array): 6 x 1
B (3d array): 1 x 6 x 4
Result (3d array): 1 x 6 x 4
A (4d array): 3 x 1 x 6 x 1
B (3d array): 2 x 1 x 4
Result (4d array): 3 x 2 x 6 x 4
Square Peg in a Round HoleSquare Peg in a Round Hole
If the dimensions do not match up, np.newaxis may be useful
In [16]: a = np.arange(6).reshape((2, 3))
In [17]: b = np.array([10, 100])
In [18]: a * b
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 a * b
ValueError: operands could not be broadcast together with shapes (2,3) (2)
In [19]: b[:,np.newaxis].shape
Out[19]: (2, 1)
In [20]: a *b[:,np.newaxis]
Out[20]:
array([[ 0, 10, 20],
[300, 400, 500]])
Array MethodsArray Methods
Predicates
a.any(), a.all()
Reductions
a.mean(), a.argmin(), a.argmax(), a.trace(),
a.cumsum(), a.cumprod()
Manipulation
a.argsort(), a.transpose(), a.reshape(...),
a.ravel(), a.fill(...), a.clip(...)
Complex Numbers
a.real, a.imag, a.conj()
Fancy IndexingFancy Indexing
NumPy arrays may be used to index into other arrays
In [2]: a = np.arange(15).reshape((3,5))
In [3]: a
Out[3]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
In [4]: i = np.array([[0,1], [1, 2]])
In [5]: j = np.array([[2, 1], [4, 4]])
In [6]: a[i,j]
Out[6]:
array([[ 2, 6],
[ 9, 14]])
Boolean arrays can also be used as indices into other arrays
In [2]: a = np.arange(15).reshape((3,5))
In [3]: a
Out[3]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
In [4]: b = (a % 3 == 0)
In [5]: b
Out[5]:
array([[ True, False, False, True, False],
[False, True, False, False, True],
[False, False, True, False, False]], dtype=bool)
In [6]: a[b]
Out[6]: array([ 0, 3, 6, 9, 12])
NumPy FunctionsNumPy Functions
Data I/O
fromfile, genfromtxt, load, loadtxt, save, savetxt
Mesh Creation
mgrid, meshgrid, ogrid
Manipulation
einsum, hstack, take, vstack
Array SubclassesArray Subclasses
numpy.ma — Masked arrays
numpy.matrix — Matrix operators
numpy.memmap — Memory-mapped arrays
numpy.recarray — Record arrays
Other SubpackagesOther Subpackages
numpy.fft — Fast Fourier transforms
numpy.polynomial — Efficient polynomials
numpy.linalg — Linear algebra
cholesky, det, eig, eigvals, inv, lstsq, norm, qr,
svd
numpy.math — C standard library math functions
numpy.random — Random number generation
beta, gamma, geometric, hypergeometric, lognormal,
normal, poisson, uniform, weibull
ExamplesExamples
FFTFFT
import numpy as np
t = np.linspace(0,120,4000)
PI = np.pi
signal = 12*np.sin(3 * 2*PI*t) # 3 Hz
signal += 6*np.sin(8 * 2*PI*t) # 8 Hz
signal += 1.5*np.random.random(len(t)) # noise
FFT = abs(np.fft.fft(signal))
freqs = np.fft.fftfreq(signal.size, t[1]-t[0])
Introduction to NumPy (PyData SV 2013)
DemosDemos
ResourcesResources
These slides are currently available at
http://docs.scipy.org/doc/numpy/reference/
http://docs.scipy.org/doc/numpy/user/index.html
http://www.scipy.org/Tentative_NumPy_Tutorial
http://www.scipy.org/Numpy_Example_List
https://github.com/ContinuumIO/tutorials/blob/master/IntrotoNumPy.pdf
The EndThe End
Many thanks toMany thanks to
Ben Zaitlin
Stéfan van der Walt
Amy Troschinetz
Maggie Mari
Travis Oliphant
Questions?Questions?

More Related Content

What's hot (20)

PPT
Python Pandas
Sunil OS
 
PDF
Python libraries
Prof. Dr. K. Adisesha
 
PPTX
List in Python
Siddique Ibrahim
 
PDF
Strings in python
Prabhakaran V M
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PDF
Python set
Mohammed Sikander
 
PDF
Pandas
maikroeder
 
PPTX
Python Scipy Numpy
Girish Khanzode
 
PPTX
PPT on Data Science Using Python
NishantKumar1179
 
PPTX
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch
 
PPTX
Introduction to python
Ayshwarya Baburam
 
PPTX
File handling in Python
Megha V
 
PPTX
heap Sort Algorithm
Lemia Algmri
 
PPTX
Data Analysis with Python Pandas
Neeru Mittal
 
PDF
Introduction To Python
Vanessa Rene
 
PPTX
Data structures and algorithms
Julie Iskander
 
PPTX
Introduction to numpy
Gaurav Aggarwal
 
PDF
Python made easy
Abhishek kumar
 
PDF
Data structure ppt
Prof. Dr. K. Adisesha
 
PPT
Python ppt
Mohita Pandey
 
Python Pandas
Sunil OS
 
Python libraries
Prof. Dr. K. Adisesha
 
List in Python
Siddique Ibrahim
 
Strings in python
Prabhakaran V M
 
Regular expressions in Python
Sujith Kumar
 
Python set
Mohammed Sikander
 
Pandas
maikroeder
 
Python Scipy Numpy
Girish Khanzode
 
PPT on Data Science Using Python
NishantKumar1179
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch
 
Introduction to python
Ayshwarya Baburam
 
File handling in Python
Megha V
 
heap Sort Algorithm
Lemia Algmri
 
Data Analysis with Python Pandas
Neeru Mittal
 
Introduction To Python
Vanessa Rene
 
Data structures and algorithms
Julie Iskander
 
Introduction to numpy
Gaurav Aggarwal
 
Python made easy
Abhishek kumar
 
Data structure ppt
Prof. Dr. K. Adisesha
 
Python ppt
Mohita Pandey
 

Viewers also liked (18)

PDF
Data Analytics with Pandas and Numpy - Python
Chetan Khatri
 
PDF
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...
Ryan Rosario
 
PDF
Tutorial de numpy
Diego Camilo Peña Ramirez
 
PDF
Scipy, numpy and friends
Michele Mattioni
 
DOCX
RobertJMontgomeryJR V4
Robert Montgomery
 
DOCX
Mart6ha
jose gonzalo garcia
 
PDF
Davidson Capital - NOAH15 London
NOAH Advisors
 
PPTX
Publication plan slideshare
caitlinhardinASmedia
 
PPTX
Data science bootcamp day2
Chetan Khatri
 
PDF
Continuous Deployment with Containers
David Papp
 
PPTX
FCA Intern Presentation
Kendall Moore
 
DOCX
News Release
Charlisa Bailey
 
TXT
Filme terror 2013
Rafael Wolf
 
PDF
Numpy, the Python foundation for number crunching
Data Science London
 
PPTX
Job fair at seattle
zeenatkassam
 
PPTX
LEÇON 127 – Il n’est d’amour que celui de Dieu.
Pierrot Caron
 
PDF
Alumni talk-university-of-kachchh
Chetan Khatri
 
PPTX
Romance powerpoint
betha2media
 
Data Analytics with Pandas and Numpy - Python
Chetan Khatri
 
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...
Ryan Rosario
 
Tutorial de numpy
Diego Camilo Peña Ramirez
 
Scipy, numpy and friends
Michele Mattioni
 
RobertJMontgomeryJR V4
Robert Montgomery
 
Davidson Capital - NOAH15 London
NOAH Advisors
 
Publication plan slideshare
caitlinhardinASmedia
 
Data science bootcamp day2
Chetan Khatri
 
Continuous Deployment with Containers
David Papp
 
FCA Intern Presentation
Kendall Moore
 
News Release
Charlisa Bailey
 
Filme terror 2013
Rafael Wolf
 
Numpy, the Python foundation for number crunching
Data Science London
 
Job fair at seattle
zeenatkassam
 
LEÇON 127 – Il n’est d’amour que celui de Dieu.
Pierrot Caron
 
Alumni talk-university-of-kachchh
Chetan Khatri
 
Romance powerpoint
betha2media
 
Ad

Similar to Introduction to NumPy (PyData SV 2013) (20)

PPTX
NumPy.pptx
EN1036VivekSingh
 
PPTX
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
tahirnaquash2
 
PPTX
NUMPY [Autosaved] .pptx
coolmanbalu123
 
PDF
Essential numpy before you start your Machine Learning journey in python.pdf
Smrati Kumar Katiyar
 
PPTX
NUMPY LIBRARY study materials PPT 2.pptx
CHETHANKUMAR274045
 
PPTX
NUMPY-2.pptx
MahendraVusa
 
PPTX
Introduction-to-NumPy-in-Python (1).pptx
disserdekabrcha
 
PPTX
Numpy in python, Array operations using numpy and so on
SherinRappai
 
PPTX
Lecture 2 _Foundions foundions NumPyI.pptx
disserdekabrcha
 
PDF
Numpy ndarrays.pdf
SudhanshiBakre1
 
PPTX
UNIT-03_Numpy (1) python yeksodbbsisbsjsjsh
tony8553004135
 
PDF
Numpy python cheat_sheet
Zahid Hasan
 
PDF
Numpy python cheat_sheet
Nishant Upadhyay
 
PDF
‏‏Lecture 2.pdf
AhmedAbdalla903058
 
PPT
CAP776Numpy (2).ppt
ChhaviCoachingCenter
 
PPT
CAP776Numpy.ppt
kdr52121
 
PDF
Numpy.pdf
Arvind Pathak
 
PDF
Python_cheatsheet_numpy.pdf
AnonymousUser67
 
PPTX
Chapter 5-Numpy-Pandas.pptx python programming
ssuser77162c
 
PDF
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
DineshThallapelly
 
NumPy.pptx
EN1036VivekSingh
 
NumPy-python-27-9-24-we.pptxNumPy-python-27-9-24-we.pptx
tahirnaquash2
 
NUMPY [Autosaved] .pptx
coolmanbalu123
 
Essential numpy before you start your Machine Learning journey in python.pdf
Smrati Kumar Katiyar
 
NUMPY LIBRARY study materials PPT 2.pptx
CHETHANKUMAR274045
 
NUMPY-2.pptx
MahendraVusa
 
Introduction-to-NumPy-in-Python (1).pptx
disserdekabrcha
 
Numpy in python, Array operations using numpy and so on
SherinRappai
 
Lecture 2 _Foundions foundions NumPyI.pptx
disserdekabrcha
 
Numpy ndarrays.pdf
SudhanshiBakre1
 
UNIT-03_Numpy (1) python yeksodbbsisbsjsjsh
tony8553004135
 
Numpy python cheat_sheet
Zahid Hasan
 
Numpy python cheat_sheet
Nishant Upadhyay
 
‏‏Lecture 2.pdf
AhmedAbdalla903058
 
CAP776Numpy (2).ppt
ChhaviCoachingCenter
 
CAP776Numpy.ppt
kdr52121
 
Numpy.pdf
Arvind Pathak
 
Python_cheatsheet_numpy.pdf
AnonymousUser67
 
Chapter 5-Numpy-Pandas.pptx python programming
ssuser77162c
 
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
DineshThallapelly
 
Ad

More from PyData (20)

PDF
Michal Mucha: Build and Deploy an End-to-end Streaming NLP Insight System | P...
PyData
 
PDF
Unit testing data with marbles - Jane Stewart Adams, Leif Walsh
PyData
 
PDF
The TileDB Array Data Storage Manager - Stavros Papadopoulos, Jake Bolewski
PyData
 
PDF
Using Embeddings to Understand the Variance and Evolution of Data Science... ...
PyData
 
PDF
Deploying Data Science for Distribution of The New York Times - Anne Bauer
PyData
 
PPTX
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
PyData
 
PPTX
Do Your Homework! Writing tests for Data Science and Stochastic Code - David ...
PyData
 
PDF
RESTful Machine Learning with Flask and TensorFlow Serving - Carlo Mazzaferro
PyData
 
PDF
Mining dockless bikeshare and dockless scootershare trip data - Stefanie Brod...
PyData
 
PDF
Avoiding Bad Database Surprises: Simulation and Scalability - Steven Lott
PyData
 
PDF
Words in Space - Rebecca Bilbro
PyData
 
PDF
End-to-End Machine learning pipelines for Python driven organizations - Nick ...
PyData
 
PPTX
Pydata beautiful soup - Monica Puerto
PyData
 
PDF
1D Convolutional Neural Networks for Time Series Modeling - Nathan Janos, Jef...
PyData
 
PPTX
Extending Pandas with Custom Types - Will Ayd
PyData
 
PDF
Measuring Model Fairness - Stephen Hoover
PyData
 
PDF
What's the Science in Data Science? - Skipper Seabold
PyData
 
PDF
Applying Statistical Modeling and Machine Learning to Perform Time-Series For...
PyData
 
PDF
Solving very simple substitution ciphers algorithmically - Stephen Enright-Ward
PyData
 
PDF
The Face of Nanomaterials: Insightful Classification Using Deep Learning - An...
PyData
 
Michal Mucha: Build and Deploy an End-to-end Streaming NLP Insight System | P...
PyData
 
Unit testing data with marbles - Jane Stewart Adams, Leif Walsh
PyData
 
The TileDB Array Data Storage Manager - Stavros Papadopoulos, Jake Bolewski
PyData
 
Using Embeddings to Understand the Variance and Evolution of Data Science... ...
PyData
 
Deploying Data Science for Distribution of The New York Times - Anne Bauer
PyData
 
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
PyData
 
Do Your Homework! Writing tests for Data Science and Stochastic Code - David ...
PyData
 
RESTful Machine Learning with Flask and TensorFlow Serving - Carlo Mazzaferro
PyData
 
Mining dockless bikeshare and dockless scootershare trip data - Stefanie Brod...
PyData
 
Avoiding Bad Database Surprises: Simulation and Scalability - Steven Lott
PyData
 
Words in Space - Rebecca Bilbro
PyData
 
End-to-End Machine learning pipelines for Python driven organizations - Nick ...
PyData
 
Pydata beautiful soup - Monica Puerto
PyData
 
1D Convolutional Neural Networks for Time Series Modeling - Nathan Janos, Jef...
PyData
 
Extending Pandas with Custom Types - Will Ayd
PyData
 
Measuring Model Fairness - Stephen Hoover
PyData
 
What's the Science in Data Science? - Skipper Seabold
PyData
 
Applying Statistical Modeling and Machine Learning to Perform Time-Series For...
PyData
 
Solving very simple substitution ciphers algorithmically - Stephen Enright-Ward
PyData
 
The Face of Nanomaterials: Insightful Classification Using Deep Learning - An...
PyData
 

Recently uploaded (20)

PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 

Introduction to NumPy (PyData SV 2013)

  • 2. What is NumPyWhat is NumPy
  • 3. NumPy is a Python C extension library for array-oriented computing Efficient In-memory Contiguous (or Strided) Homogeneous (but types can be algebraic) NumPy is suited to many applications Image processing Signal processing Linear algebra A plethora of others
  • 4. NumPy is the foundation of theNumPy is the foundation of the python scientific stackpython scientific stack
  • 6. Quick StartQuick Start In [1]: import numpy as np In [2]: a = np.array([1,2,3,4,5,6,7,8,9]) In [3]: a Out[3]: array([1, 2, 3, 4, 5, 6, 7, 8, 9]) In [4]: b = a.reshape((3,3)) In [5]: b Out[5]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) In [6]: b * 10 + 4 Out[6]: array([[14, 24, 34], [44, 54, 64], [74, 84, 94]])
  • 7. Array ShapeArray Shape One dimensional arrays have a 1-tuple forOne dimensional arrays have a 1-tuple for their shapetheir shape
  • 8. ...Two dimensional arrays have a 2-tuple...Two dimensional arrays have a 2-tuple
  • 10. Array Element Type (dtype)Array Element Type (dtype) NumPy arrays comprise elements of a single data type The type object is accessible through the .dtype attribute Here are a few of the most important attributes of dtype objects dtype.byteorder — big or little endian dtype.itemsize — element size of this dtype dtype.name — a name for this dtype object dtype.type — type object used to create scalars There are many others...
  • 11. Array dtypes are usually inferred automatically But can also be specified explicitly In [16]: a = np.array([1,2,3]) In [17]: a.dtype Out[17]: dtype('int64') In [18]: b = np.array([1,2,3,4.567]) In [19]: b.dtype Out[19]: dtype('float64') In [20]: a = np.array([1,2,3], dtype=np.float32) In [21]: a.dtype Out[21]: dtype('int64') In [22]: a Out[22]: array([ 1., 2., 3.], dtype=float32)
  • 12. NumPy Builtin dtype HierarchyNumPy Builtin dtype Hierarchy np.datetime64 is a new addition in NumPy 1.7
  • 13. Array CreationArray Creation Explicitly from a list of values As a range of values By specifying the number of elements In [2]: np.array([1,2,3,4]) Out[2]: array([1, 2, 3, 4]) In [3]: np.arange(10) Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [4]: np.linspace(0, 1, 5) Out[4]: array([ 0. , 0.25, 0.5 , 0.75, 1. ])
  • 14. Zero-initialized One-initialized Uninitialized In [4]: np.zeros((2,2)) Out[4]: array([[ 0., 0.], [ 0., 0.]]) In [5]: np.ones((1,5)) Out[5]: array([[ 1., 1., 1., 1., 1.]]) In [4]: np.empty((1,3)) Out[4]: array([[ 2.12716633e-314, 2.12716633e-314, 2.15203762e-314]])
  • 15. Constant diagonal value Multiple diagonal values In [6]: np.eye(3) Out[6]: array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) In [7]: np.diag([1,2,3,4]) Out[7]: array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]])
  • 16. Array Memory LayoutArray Memory Layout
  • 19. NumPy array indices can also take an optional stride
  • 20. Array ViewsArray Views Simple assigments do not make copies of arrays (same semantics as Python). Slicing operations do not make copies either; they return views on the original array. Array views contain a pointer to the original data, but may have different shape or stride values. Views always have flags.owndata equal to False. In [2]: a = np.arange(10) In [3]: b = a[3:7] In [4]: b Out[4]: array([3, 4, 5, 6]) In [5]: b[:] = 0 In [6]: a Out[6]: array([0, 1, 3, 0, 0, 0, 0, 7, 8, 9]) In [7]: b.flags.owndata Out[7]: False
  • 21. Universal Functions (ufuncs)Universal Functions (ufuncs) NumPy ufuncs are functions that operate element-wise on one or more arrays ufuncs dispatch to optimized C inner-loops based on array dtype
  • 22. NumPy has many built-in ufuncsNumPy has many built-in ufuncs comparison: <, <=, ==, !=, >=, > arithmetic: +, -, *, /, reciprocal, square exponential: exp, expm1, exp2, log, log10, log1p, log2, power, sqrt trigonometric: sin, cos, tan, acsin, arccos, atctan hyperbolic: sinh, cosh, tanh, acsinh, arccosh, atctanh bitwise operations: &, |, ~, ^, left_shift, right_shift logical operations: and, logical_xor, not, or predicates: isfinite, isinf, isnan, signbit other: abs, ceil, floor, mod, modf, round, sinc, sign, trunc
  • 23. AxisAxis Array method reductions take an optional axis parameter that specifies over which axes to reduce axis=None reduces into a single scalar In [7]: a.sum () Out[7]: 105
  • 24. axis=None is the default
  • 25. axis=0 reduces into the zeroth dimension axis=0 reduces into the first dimension In [8]: a.sum(axis=0) Out[8]: array([15, 18, 21, 24, 27]) In [9]: a.sum(axis=1) Out[9]: array([10, 35, 60])
  • 26. BroadcastingBroadcasting A key feature of NumPy is broadcasting, where arrays with different, but compatible shapes can be used as arguments to ufuncs In this case an array scalar is broadcast to an array with shape (5, )
  • 27. A slightly more involved broadcasting example in two dimensions Here an array of shape (3, 1) is broadcast to an array with shape (3, 2)
  • 28. Broadcasting RulesBroadcasting Rules In order for an operation to broadcast, the size of all the trailing dimensions for both arrays must either: be equal OR be one A (1d array): 3 B (2d array): 2 x 3 Result (2d array): 2 x 3 A (2d array): 6 x 1 B (3d array): 1 x 6 x 4 Result (3d array): 1 x 6 x 4 A (4d array): 3 x 1 x 6 x 1 B (3d array): 2 x 1 x 4 Result (4d array): 3 x 2 x 6 x 4
  • 29. Square Peg in a Round HoleSquare Peg in a Round Hole If the dimensions do not match up, np.newaxis may be useful In [16]: a = np.arange(6).reshape((2, 3)) In [17]: b = np.array([10, 100]) In [18]: a * b --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () ----> 1 a * b ValueError: operands could not be broadcast together with shapes (2,3) (2) In [19]: b[:,np.newaxis].shape Out[19]: (2, 1) In [20]: a *b[:,np.newaxis] Out[20]: array([[ 0, 10, 20], [300, 400, 500]])
  • 30. Array MethodsArray Methods Predicates a.any(), a.all() Reductions a.mean(), a.argmin(), a.argmax(), a.trace(), a.cumsum(), a.cumprod() Manipulation a.argsort(), a.transpose(), a.reshape(...), a.ravel(), a.fill(...), a.clip(...) Complex Numbers a.real, a.imag, a.conj()
  • 31. Fancy IndexingFancy Indexing NumPy arrays may be used to index into other arrays In [2]: a = np.arange(15).reshape((3,5)) In [3]: a Out[3]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) In [4]: i = np.array([[0,1], [1, 2]]) In [5]: j = np.array([[2, 1], [4, 4]]) In [6]: a[i,j] Out[6]: array([[ 2, 6], [ 9, 14]])
  • 32. Boolean arrays can also be used as indices into other arrays In [2]: a = np.arange(15).reshape((3,5)) In [3]: a Out[3]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) In [4]: b = (a % 3 == 0) In [5]: b Out[5]: array([[ True, False, False, True, False], [False, True, False, False, True], [False, False, True, False, False]], dtype=bool) In [6]: a[b] Out[6]: array([ 0, 3, 6, 9, 12])
  • 33. NumPy FunctionsNumPy Functions Data I/O fromfile, genfromtxt, load, loadtxt, save, savetxt Mesh Creation mgrid, meshgrid, ogrid Manipulation einsum, hstack, take, vstack
  • 34. Array SubclassesArray Subclasses numpy.ma — Masked arrays numpy.matrix — Matrix operators numpy.memmap — Memory-mapped arrays numpy.recarray — Record arrays
  • 35. Other SubpackagesOther Subpackages numpy.fft — Fast Fourier transforms numpy.polynomial — Efficient polynomials numpy.linalg — Linear algebra cholesky, det, eig, eigvals, inv, lstsq, norm, qr, svd numpy.math — C standard library math functions numpy.random — Random number generation beta, gamma, geometric, hypergeometric, lognormal, normal, poisson, uniform, weibull
  • 37. FFTFFT import numpy as np t = np.linspace(0,120,4000) PI = np.pi signal = 12*np.sin(3 * 2*PI*t) # 3 Hz signal += 6*np.sin(8 * 2*PI*t) # 8 Hz signal += 1.5*np.random.random(len(t)) # noise FFT = abs(np.fft.fft(signal)) freqs = np.fft.fftfreq(signal.size, t[1]-t[0])
  • 40. ResourcesResources These slides are currently available at http://docs.scipy.org/doc/numpy/reference/ http://docs.scipy.org/doc/numpy/user/index.html http://www.scipy.org/Tentative_NumPy_Tutorial http://www.scipy.org/Numpy_Example_List https://github.com/ContinuumIO/tutorials/blob/master/IntrotoNumPy.pdf
  • 41. The EndThe End Many thanks toMany thanks to Ben Zaitlin Stéfan van der Walt Amy Troschinetz Maggie Mari Travis Oliphant Questions?Questions?