SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
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
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])
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?

Contenu connexe

Tendances

Intoduction to numpy
Intoduction to numpyIntoduction to numpy
Intoduction to numpyFaraz Ahmed
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPyDevashish Kumar
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Data Visualization in Python
Data Visualization in PythonData Visualization in Python
Data Visualization in PythonJagriti Goswami
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python PandasNeeru Mittal
 
Data visualization in Python
Data visualization in PythonData visualization in Python
Data visualization in PythonMarc Garcia
 
Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1Jatin Miglani
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Edureka!
 

Tendances (20)

Intoduction to numpy
Intoduction to numpyIntoduction to numpy
Intoduction to numpy
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Python list
Python listPython list
Python list
 
Data Visualization in Python
Data Visualization in PythonData Visualization in Python
Data Visualization in Python
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
Data visualization in Python
Data visualization in PythonData visualization in Python
Data visualization in Python
 
Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
List in Python
List in PythonList in Python
List in Python
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
 

En vedette

Data Analytics with Pandas and Numpy - Python
Data Analytics with Pandas and Numpy - PythonData Analytics with Pandas and Numpy - Python
Data Analytics with Pandas and Numpy - PythonChetan Khatri
 
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...Ryan Rosario
 
Davidson Capital - NOAH15 London
Davidson Capital - NOAH15 LondonDavidson Capital - NOAH15 London
Davidson Capital - NOAH15 LondonNOAH Advisors
 
Data science bootcamp day2
Data science bootcamp day2Data science bootcamp day2
Data science bootcamp day2Chetan Khatri
 
Continuous Deployment with Containers
Continuous Deployment with ContainersContinuous Deployment with Containers
Continuous Deployment with ContainersDavid Papp
 
FCA Intern Presentation
FCA Intern PresentationFCA Intern Presentation
FCA Intern PresentationKendall Moore
 
Filme terror 2013
Filme terror 2013Filme terror 2013
Filme terror 2013Rafael Wolf
 
Numpy, the Python foundation for number crunching
Numpy, the Python foundation for number crunchingNumpy, the Python foundation for number crunching
Numpy, the Python foundation for number crunchingData Science London
 
Job fair at seattle
Job fair at seattleJob fair at seattle
Job fair at seattlezeenatkassam
 
LEÇON 127 – Il n’est d’amour que celui de Dieu.
LEÇON 127 – Il n’est d’amour que celui de Dieu.LEÇON 127 – Il n’est d’amour que celui de Dieu.
LEÇON 127 – Il n’est d’amour que celui de Dieu.Pierrot Caron
 
Alumni talk-university-of-kachchh
Alumni talk-university-of-kachchhAlumni talk-university-of-kachchh
Alumni talk-university-of-kachchhChetan Khatri
 
Romance powerpoint
Romance powerpointRomance powerpoint
Romance powerpointbetha2media
 

En vedette (19)

Data Analytics with Pandas and Numpy - Python
Data Analytics with Pandas and Numpy - PythonData Analytics with Pandas and Numpy - Python
Data Analytics with Pandas and Numpy - Python
 
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...
NumPy and SciPy for Data Mining and Data Analysis Including iPython, SciKits,...
 
Tutorial de numpy
Tutorial de numpyTutorial de numpy
Tutorial de numpy
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
Scipy, numpy and friends
Scipy, numpy and friendsScipy, numpy and friends
Scipy, numpy and friends
 
RobertJMontgomeryJR V4
RobertJMontgomeryJR V4RobertJMontgomeryJR V4
RobertJMontgomeryJR V4
 
Mart6ha
Mart6haMart6ha
Mart6ha
 
Davidson Capital - NOAH15 London
Davidson Capital - NOAH15 LondonDavidson Capital - NOAH15 London
Davidson Capital - NOAH15 London
 
Publication plan slideshare
Publication plan slidesharePublication plan slideshare
Publication plan slideshare
 
Data science bootcamp day2
Data science bootcamp day2Data science bootcamp day2
Data science bootcamp day2
 
Continuous Deployment with Containers
Continuous Deployment with ContainersContinuous Deployment with Containers
Continuous Deployment with Containers
 
FCA Intern Presentation
FCA Intern PresentationFCA Intern Presentation
FCA Intern Presentation
 
News Release
News ReleaseNews Release
News Release
 
Filme terror 2013
Filme terror 2013Filme terror 2013
Filme terror 2013
 
Numpy, the Python foundation for number crunching
Numpy, the Python foundation for number crunchingNumpy, the Python foundation for number crunching
Numpy, the Python foundation for number crunching
 
Job fair at seattle
Job fair at seattleJob fair at seattle
Job fair at seattle
 
LEÇON 127 – Il n’est d’amour que celui de Dieu.
LEÇON 127 – Il n’est d’amour que celui de Dieu.LEÇON 127 – Il n’est d’amour que celui de Dieu.
LEÇON 127 – Il n’est d’amour que celui de Dieu.
 
Alumni talk-university-of-kachchh
Alumni talk-university-of-kachchhAlumni talk-university-of-kachchh
Alumni talk-university-of-kachchh
 
Romance powerpoint
Romance powerpointRomance powerpoint
Romance powerpoint
 

Similaire à Introduction to NumPy (PyData SV 2013)

NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxJohnWilliam111370
 
NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptxcoolmanbalu123
 
Essential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdfEssential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdfSmrati Kumar Katiyar
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
Python_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdfPython_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdfAnonymousUser67
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheetZahid Hasan
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.pptkdr52121
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
 
Numpy in Python.docx
Numpy in Python.docxNumpy in Python.docx
Numpy in Python.docxmanohar25689
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptadityavarte
 
arraycreation.pptx
arraycreation.pptxarraycreation.pptx
arraycreation.pptxsathya930629
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonLifna C.S
 

Similaire à Introduction to NumPy (PyData SV 2013) (20)

NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptx
 
NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptx
 
Essential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdfEssential numpy before you start your Machine Learning journey in python.pdf
Essential numpy before you start your Machine Learning journey in python.pdf
 
14078956.ppt
14078956.ppt14078956.ppt
14078956.ppt
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
Python_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdfPython_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdf
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
Numpy - Array.pdf
Numpy - Array.pdfNumpy - Array.pdf
Numpy - Array.pdf
 
CAP776Numpy (2).ppt
CAP776Numpy (2).pptCAP776Numpy (2).ppt
CAP776Numpy (2).ppt
 
CAP776Numpy.ppt
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.ppt
 
NUMPY-2.pptx
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptx
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
PPS-UNIT5.ppt
PPS-UNIT5.pptPPS-UNIT5.ppt
PPS-UNIT5.ppt
 
Numpy in Python.docx
Numpy in Python.docxNumpy in Python.docx
Numpy in Python.docx
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
 
arraycreation.pptx
arraycreation.pptxarraycreation.pptx
arraycreation.pptx
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 

Plus de PyData

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

Plus de PyData (20)

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

Dernier

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Dernier (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 

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
  • 18.
  • 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])
  • 38.
  • 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?