0% found this document useful (0 votes)
111 views

Numpy PDF

The document discusses NumPy arrays and their basic usage. It introduces importing NumPy, creating arrays, array attributes like shape and dtype, and NumPy's built-in datatypes like int, float, complex. Arrays can represent all types of data and are useful for many tasks. Once created, an array's dtype cannot be changed.

Uploaded by

Ananda Dasgupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views

Numpy PDF

The document discusses NumPy arrays and their basic usage. It introduces importing NumPy, creating arrays, array attributes like shape and dtype, and NumPy's built-in datatypes like int, float, complex. Arrays can represent all types of data and are useful for many tasks. Once created, an array's dtype cannot be changed.

Uploaded by

Ananda Dasgupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 273

The Numpy Array

Ananda Dasgupta

Indian Institute of Science Education and Research Kolkata

Ananda Dasgupta The Numpy Array 1 / 57


Starting out with Numpy

The basic mantra

import numpy as np

Ananda Dasgupta The Numpy Array 2 / 57


Starting out with Numpy

The basic mantra

import numpy as np

Once this is done, you can use the goodies provided by numpy
using the np.goody_name format!

Ananda Dasgupta The Numpy Array 2 / 57


Starting out with Numpy

The basic mantra

import numpy as np

Once this is done, you can use the goodies provided by numpy
using the np.goody_name format!

The most useful object that numpy provides is the array

Ananda Dasgupta The Numpy Array 2 / 57


Starting out with Numpy

The basic mantra

import numpy as np

Once this is done, you can use the goodies provided by numpy
using the np.goody_name format!

The most useful object that numpy provides is the array

Creating an array is easy!

aa = np.array([[1,2],[3,4],[5,6]])

Ananda Dasgupta The Numpy Array 2 / 57


Starting out with Numpy

The basic mantra

import numpy as np

Once this is done, you can use the goodies provided by numpy
using the np.goody_name format!

The most useful object that numpy provides is the array

Creating an array is easy!

aa = np.array([[1,2],[3,4],[5,6]])

This creates a 3 ×2 array of integers!

Ananda Dasgupta The Numpy Array 2 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 3 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 4 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 4 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 4 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 4 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 4 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 4 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 5 / 57


Arrays : what are they good for?
Absolutely everything!!!

Ananda Dasgupta The Numpy Array 5 / 57


Array Attributes

size Total number of elements in the array


aa.size 6

Ananda Dasgupta The Numpy Array 6 / 57


Array Attributes

size Total number of elements in the array


aa.size 6
shape A tuple that holds the number of
elements for each axis (dimension) of the array
aa.shape (3,2)

Ananda Dasgupta The Numpy Array 6 / 57


Array Attributes

size Total number of elements in the array


aa.size 6
shape A tuple that holds the number of
elements for each axis (dimension) of the array
aa.shape (3,2)
ndim Number of axes (dimensions)
aa.ndim 2

Ananda Dasgupta The Numpy Array 6 / 57


Array Attributes

size Total number of elements in the array


aa.size 6
shape A tuple that holds the number of
elements for each axis (dimension) of the array
aa.shape (3,2)
ndim Number of axes (dimensions)
aa.ndim 2
nbytes Number of bytes used to store the data
aa.nbytes 48

Ananda Dasgupta The Numpy Array 6 / 57


Array Attributes

size Total number of elements in the array


aa.size 6
shape A tuple that holds the number of
elements for each axis (dimension) of the array
aa.shape (3,2)
ndim Number of axes (dimensions)
aa.ndim 2
nbytes Number of bytes used to store the data
aa.nbytes 48
dtype The data type of elements in the array
aa.dtype dtype('int64')

Ananda Dasgupta The Numpy Array 6 / 57


The numpy dtypes
dtype variants Description
int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes
dtype variants Description
int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

np.array([1,2,3],dtype=int) [1,2,3]

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes
dtype variants Description
int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

np.array([1,2,3],dtype=int) [1,2,3]
np.array([1,2,3],dtype=oat) [1.,2.,3.]

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes
dtype variants Description
int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

np.array([1,2,3],dtype=int) [1,2,3]
np.array([1,2,3],dtype=oat) [1.,2.,3.]
np.array([1,2,3],dtype=complex) [1.+0.j,2.+0.j,3.+0.j]

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes

dtype variants Description


int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes

dtype variants Description


int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

Once created, a numpy array's dtype can not be changed!

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes

dtype variants Description


int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

Once created, a numpy array's dtype can not be changed!


You can, however, create copies with type-casted data!

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes
dtype variants Description
int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

Once created, a numpy array's dtype can not be changed!


You can, however, create copies with type-casted data!
aa = np.array([1,2,3],dtype=int) [1,2,3]

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes
dtype variants Description
int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

Once created, a numpy array's dtype can not be changed!


You can, however, create copies with type-casted data!
aa = np.array([1,2,3],dtype=int) [1,2,3]
bb = np.array(aa,dtype=oat) [1.,2.,3.]

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes
dtype variants Description
int int8, int16, int32, Integers
int64
uint uint8, uint16, Unsigned (nonnegative) integers
uint32, uint64
bool Bool Boolean (True or False)
oat oat16, oat32, Floating-point numbers
oat64, oat128
complex complex64, Complex-valued oating-point numbers
complex128,
complex256

Once created, a numpy array's dtype can not be changed!


You can, however, create copies with type-casted data!
aa = np.array([1,2,3],dtype=int) [1,2,3]
bb = aa.astype(oat) [1.,2.,3.]

Ananda Dasgupta The Numpy Array 7 / 57


The numpy dtypes
Do we need to worry about them?

Ananda Dasgupta The Numpy Array 8 / 57


The numpy dtypes
Do we need to worry about them?

Ananda Dasgupta The Numpy Array 8 / 57


The numpy dtypes
Do we need to worry about them?

Ananda Dasgupta The Numpy Array 8 / 57


Creating numpy arrays
From lists and other similar objects

li = [1,2,3,4]

Ananda Dasgupta The Numpy Array 9 / 57


Creating numpy arrays
From lists and other similar objects

li = [1,2,3,4]
aa = np.array(li)
array([1,2,3,4])

Ananda Dasgupta The Numpy Array 9 / 57


Creating numpy arrays
From lists and other similar objects

li = [1,2,3,4]
aa = np.array(li)
array([1,2,3,4])
aa.ndim
1

Ananda Dasgupta The Numpy Array 9 / 57


Creating numpy arrays
From lists and other similar objects

li = [1,2,3,4]
aa = np.array(li)
array([1,2,3,4])
aa.ndim
1
aa.shape
(4,)

Ananda Dasgupta The Numpy Array 9 / 57


Creating numpy arrays
From lists and other similar objects

li = [[1,2],[3,4]]

Ananda Dasgupta The Numpy Array 10 / 57


Creating numpy arrays
From lists and other similar objects

li = [[1,2],[3,4]]
aa = np.array(li)
array([[1,2],
[3,4]])

Ananda Dasgupta The Numpy Array 10 / 57


Creating numpy arrays
From lists and other similar objects

li = [[1,2],[3,4]]
aa = np.array(li)
array([[1,2],
[3,4]])
aa.ndim
2

Ananda Dasgupta The Numpy Array 10 / 57


Creating numpy arrays
From lists and other similar objects

li = [[1,2],[3,4]]
aa = np.array(li)
array([[1,2],
[3,4]])
aa.ndim
2
aa.shape
(2,2)

Ananda Dasgupta The Numpy Array 10 / 57


Creating numpy arrays
Creating arrays lled with constants

np.zeros((2, 3))
array([[ 0., 0., 0.],
[ 0., 0., 0.]])

Ananda Dasgupta The Numpy Array 11 / 57


Creating numpy arrays
Creating arrays lled with constants

np.zeros((2, 3))
array([[ 0., 0., 0.],
[ 0., 0., 0.]])

np.ones(4)
array([ 1., 1., 1., 1.])

Ananda Dasgupta The Numpy Array 11 / 57


Creating numpy arrays
Creating arrays lled with constants

np.zeros((2, 3))
array([[ 0., 0., 0.],
[ 0., 0., 0.]])

np.ones(4)
array([ 1., 1., 1., 1.])

np.full(4,2.5)
array([ 2.5, 2.5, 2.5, 2.5])

Ananda Dasgupta The Numpy Array 11 / 57


Creating numpy arrays
Creating arrays lled with constants

np.zeros((2, 3))
array([[ 0., 0., 0.],
[ 0., 0., 0.]])

np.ones(4)
array([ 1., 1., 1., 1.])

np.full(4,2.5)
array([ 2.5, 2.5, 2.5, 2.5])

a = np.empty(4)
a.ll(2.5)
array([ 2.5, 2.5, 2.5, 2.5])

Ananda Dasgupta The Numpy Array 11 / 57


Creating numpy arrays
Creating arrays lled with constants

np.zeros((2, 3))
array([[ 0., 0., 0.],
[ 0., 0., 0.]])

np.ones(4)
array([ 1., 1., 1., 1.])

np.full(4,2.5)
array([ 2.5, 2.5, 2.5, 2.5])

a = np.empty(4)
a.ll(2.5)
array([ 2.5, 2.5, 2.5, 2.5])

np.zeros((2, 3),dtype=int)
array([[ 0, 0, 0],
[ 0, 0, 0]])

Ananda Dasgupta The Numpy Array 11 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.arange() function is similar to python range(), but more


versatile!

Ananda Dasgupta The Numpy Array 12 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.arange() function is similar to python range(), but more


versatile!

Ananda Dasgupta The Numpy Array 12 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.arange() function is similar to python range(), but more


versatile!

Ananda Dasgupta The Numpy Array 12 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.arange() function is similar to python range(), but more


versatile!

Ananda Dasgupta The Numpy Array 12 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.arange() function is similar to python range(), but more


versatile!

Ananda Dasgupta The Numpy Array 12 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.linspace() function takes the two endpoints and number of


elements as input, and produces a equally spaced sequence.

Ananda Dasgupta The Numpy Array 13 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.linspace() function takes the two endpoints and number of


elements as input, and produces a equally spaced sequence.

Ananda Dasgupta The Numpy Array 13 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.linspace() function takes the two endpoints and number of


elements as input, and produces a equally spaced sequence.

Ananda Dasgupta The Numpy Array 13 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.linspace() function takes the two endpoints and number of


elements as input, and produces a equally spaced sequence.

Ananda Dasgupta The Numpy Array 13 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.linspace() function takes the two endpoints and number of


elements as input, and produces a equally spaced sequence.

Ananda Dasgupta The Numpy Array 13 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.logspace() function takes the two endpoints (exponents of


a base p ) and number of elements as input, and produces a
sequence of logarithmically equi-spaced numbers (numbers in GP).

Ananda Dasgupta The Numpy Array 14 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.logspace() function takes the two endpoints (exponents of


a base p ) and number of elements as input, and produces a
sequence of logarithmically equi-spaced numbers (numbers in GP).

Ananda Dasgupta The Numpy Array 14 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.logspace() function takes the two endpoints (exponents of


a base p ) and number of elements as input, and produces a
sequence of logarithmically equi-spaced numbers (numbers in GP).

Ananda Dasgupta The Numpy Array 14 / 57


Creating numpy arrays
Creating arrays lled with sequences

The np.logspace() function takes the two endpoints (exponents of


a base p ) and number of elements as input, and produces a
sequence of logarithmically equi-spaced numbers (numbers in GP).

Ananda Dasgupta The Numpy Array 14 / 57


Creating numpy arrays
Special matrix arrays

Ananda Dasgupta The Numpy Array 15 / 57


Creating numpy arrays
Special matrix arrays

Ananda Dasgupta The Numpy Array 15 / 57


Creating numpy arrays
Special matrix arrays

Ananda Dasgupta The Numpy Array 15 / 57


Creating numpy arrays
Special matrix arrays

Ananda Dasgupta The Numpy Array 15 / 57


Creating numpy arrays
Creating meshgrids

For many applications we need to create meshes of coordinates!

(−2, 2) (−1, 2) (0, 2) (1, 2) (2, 2)

(−2, 1) (−1, 1) (0, 1) (1, 1) (2, 1)

(−2, 0) (−1, 0) (0, 0) (1, 0) (2, 0)

(−2, −1)(−1, −1) (0, −1) (1, −1) (2, −1)

(−2, −2)(−1, −2) (0, −2) (1, −2) (2, −2)


Ananda Dasgupta The Numpy Array 16 / 57
Creating numpy arrays
Creating meshgrids

For many applications we need to create meshes of coordinates!

(−2, 2) (−1, 2) (0, 2) (1, 2) (2, 2)

(−2, 1) (−1, 1) (0, 1) (1, 1) (2, 1)

(−2, 0) (−1, 0) (0, 0) (1, 0) (2, 0)

(−2, −1)(−1, −1) (0, −1) (1, −1) (2, −1)

(−2, −2)(−1, −2) (0, −2) (1, −2) (2, −2)


Ananda Dasgupta The Numpy Array 16 / 57
Creating numpy arrays
Creating meshgrids

For many applications we need to create meshes of coordinates!

(−2, 2) (−1, 2) (0, 2) (1, 2) (2, 2)

(−2, 1) (−1, 1) (0, 1) (1, 1) (2, 1)

(−2, 0) (−1, 0) (0, 0) (1, 0) (2, 0)

(−2, −1)(−1, −1) (0, −1) (1, −1) (2, −1)

(−2, −2)(−1, −2) (0, −2) (1, −2) (2, −2)


Ananda Dasgupta The Numpy Array 16 / 57
Creating numpy arrays
Creating meshgrids

For many applications we need to create meshes of coordinates!

(−2, 2) (−1, 2) (0, 2) (1, 2) (2, 2)

(−2, 1) (−1, 1) (0, 1) (1, 1) (2, 1) X,Y =


np.meshgrid(xx,yy)

(−2, 0) (−1, 0) (0, 0) (1, 0) (2, 0)

(−2, −1)(−1, −1) (0, −1) (1, −1) (2, −1)

(−2, −2)(−1, −2) (0, −2) (1, −2) (2, −2)


Ananda Dasgupta The Numpy Array 16 / 57
Creating numpy arrays
Creating meshgrids

For many applications we need to create meshes of coordinates!

(−2, 2) (−1, 2) (0, 2) (1, 2) (2, 2)

(−2, 1) (−1, 1) (0, 1) (1, 1) (2, 1) X,Y =


np.meshgrid(xx,yy)

(−2, 0) (−1, 0) (0, 0) (1, 0) (2, 0)

(−2, −1)(−1, −1) (0, −1) (1, −1) (2, −1)

(−2, −2)(−1, −2) (0, −2) (1, −2) (2, −2)


Ananda Dasgupta The Numpy Array 16 / 57
Creating numpy arrays
Using meshgrids

Ananda Dasgupta The Numpy Array 17 / 57


Creating numpy arrays
Using meshgrids

Ananda Dasgupta The Numpy Array 17 / 57


Creating numpy arrays
Creating arrays like existing ones

Numpy has special methods for creating special arrays that share
properties like shape and data type with existing arrays.

Ananda Dasgupta The Numpy Array 18 / 57


Creating numpy arrays
Creating arrays like existing ones

Numpy has special methods for creating special arrays that share
properties like shape and data type with existing arrays.
a = np.array([[1,2,3],[4,5,6]])

Ananda Dasgupta The Numpy Array 18 / 57


Creating numpy arrays
Creating arrays like existing ones

Numpy has special methods for creating special arrays that share
properties like shape and data type with existing arrays.
a = np.array([[1,2,3],[4,5,6]])

Ananda Dasgupta The Numpy Array 18 / 57


Creating numpy arrays
Creating arrays like existing ones

Numpy has special methods for creating special arrays that share
properties like shape and data type with existing arrays.
a = np.array([[1,2,3],[4,5,6]])

Ananda Dasgupta The Numpy Array 18 / 57


Creating numpy arrays
Creating arrays like existing ones

Numpy has special methods for creating special arrays that share
properties like shape and data type with existing arrays.
a = np.array([[1,2,3],[4,5,6]])

Ananda Dasgupta The Numpy Array 18 / 57


Creating numpy arrays
Creating arrays like existing ones

Numpy has special methods for creating special arrays that share
properties like shape and data type with existing arrays.
a = np.array([[1,2,3],[4,5,6]])

Ananda Dasgupta The Numpy Array 18 / 57


Creating numpy arrays
Using fromfunction

The method np.fromfunction() creates an array and lls it with


values specied by a given function, which is evaluated for each
combination of indices.

Ananda Dasgupta The Numpy Array 19 / 57


Creating numpy arrays
Using fromfunction

The method np.fromfunction() creates an array and lls it with


values specied by a given function, which is evaluated for each
combination of indices.

f = lambda m,n: 10*m+n

Ananda Dasgupta The Numpy Array 19 / 57


Creating numpy arrays
Using fromfunction

The method np.fromfunction() creates an array and lls it with


values specied by a given function, which is evaluated for each
combination of indices.

f = lambda m,n: 10*m+n

Ananda Dasgupta The Numpy Array 19 / 57


Creating numpy arrays
Random arrays

The numpy.random submodule has a lot of methods to create


random arrays of specied shape.

Ananda Dasgupta The Numpy Array 20 / 57


Creating numpy arrays
Random arrays

The numpy.random submodule has a lot of methods to create


random arrays of specied shape.

Ananda Dasgupta The Numpy Array 20 / 57


Creating numpy arrays
Random arrays

The numpy.random submodule has a lot of methods to create


random arrays of specied shape.

Ananda Dasgupta The Numpy Array 20 / 57


Creating numpy arrays
Random arrays

The numpy.random submodule has a lot of methods to create


random arrays of specied shape.

Ananda Dasgupta The Numpy Array 20 / 57


Creating numpy arrays
Random arrays

Ananda Dasgupta The Numpy Array 21 / 57


Creating numpy arrays
Random arrays

Ananda Dasgupta The Numpy Array 21 / 57


Creating numpy arrays
Random arrays : Pi the numpy way!

Ananda Dasgupta The Numpy Array 22 / 57


Creating numpy arrays
Random arrays : Pi the numpy way!

Ananda Dasgupta The Numpy Array 22 / 57


Creating numpy arrays
Random arrays : Pi the numpy way!

Ananda Dasgupta The Numpy Array 22 / 57


Creating numpy arrays
Random arrays : Pi the numpy way!

Ananda Dasgupta The Numpy Array 22 / 57


Slicing up an array
Easy as py!

Ananda Dasgupta The Numpy Array 23 / 57


Slicing up an array
Easy as py!

One dimensional arrays

Ananda Dasgupta The Numpy Array 23 / 57


Slicing up an array
Easy as py!

One dimensional arrays


Indexing and slicing a 1D array is similar to lists.

Ananda Dasgupta The Numpy Array 23 / 57


Slicing up an array
Easy as py!

One dimensional arrays


Indexing and slicing a 1D array is similar to lists.
Given an array A, indexing individual elements is
done using square brackets

Ananda Dasgupta The Numpy Array 23 / 57


Slicing up an array
Easy as py!

One dimensional arrays


Indexing and slicing a 1D array is similar to lists.
Given an array A, indexing individual elements is
done using square brackets
We can read or change elements using this!

Ananda Dasgupta The Numpy Array 23 / 57


Slicing up an array
Easy as py!

One dimensional arrays


Indexing and slicing a 1D array is similar to lists.
Given an array A, indexing individual elements is
done using square brackets
We can read or change elements using this!
Negative indices count from the back.

Ananda Dasgupta The Numpy Array 23 / 57


Slicing up an array
Easy as py!

One dimensional arrays


Indexing and slicing a 1D array is similar to lists.
Given an array A, indexing individual elements is
done using square brackets
We can read or change elements using this!
Negative indices count from the back.
We can use slices using the [i :f :∆] construct.

Ananda Dasgupta The Numpy Array 23 / 57


Slicing up an array
Easy as py!

One dimensional arrays


Indexing and slicing a 1D array is similar to lists.
Given an array A, indexing individual elements is
done using square brackets
We can read or change elements using this!
Negative indices count from the back.
We can use slices using the [i :f :∆] construct.
Warning: Slices are views of the array - not
dierent arrays!!!!

Ananda Dasgupta The Numpy Array 23 / 57


Indexing and slicing 1D arrays
Accessing an element via [ ]

Ananda Dasgupta The Numpy Array 24 / 57


Indexing and slicing 1D arrays
Changing an element via [ ] Note the dtype!

Ananda Dasgupta The Numpy Array 24 / 57


Indexing and slicing 1D arrays
Negative indices count from the back!

Ananda Dasgupta The Numpy Array 24 / 57


Indexing and slicing 1D arrays
Slicing an array via [m : n]

Ananda Dasgupta The Numpy Array 24 / 57


Indexing and slicing 1D arrays
Slicing till the end or from the beginning!

Ananda Dasgupta The Numpy Array 25 / 57


Indexing and slicing 1D arrays
Slicing with jumps!

Ananda Dasgupta The Numpy Array 25 / 57


Indexing and slicing 1D arrays
Negative increments return a reversed view!

Ananda Dasgupta The Numpy Array 25 / 57


Indexing and slicing 1D arrays
Every second element, in reversed order!

Ananda Dasgupta The Numpy Array 25 / 57


Slices are views
Here B is a subarray of A

Ananda Dasgupta The Numpy Array 26 / 57


Slices are views
Changing B aects A

Ananda Dasgupta The Numpy Array 26 / 57


Slices are views
C is a copy of a subarray of A

Ananda Dasgupta The Numpy Array 26 / 57


Slices are views
Changing C has no eect on A

Ananda Dasgupta The Numpy Array 26 / 57


Indexing multidimensional arrays
You can create a multidimensional array from a list of lists.

Ananda Dasgupta The Numpy Array 27 / 57


Indexing multidimensional arrays
You can create a multidimensional array from a list of lists.

You have to access lowest level elements in the list by [ ][ ]


construct - comma separated indices don't work!

Ananda Dasgupta The Numpy Array 27 / 57


Indexing multidimensional arrays
You can create a multidimensional array from a list of lists.

You have to access lowest level elements in the list by [ ][ ]


construct - comma separated indices don't work!

Both styles work for arrays, though [m , n ] is more natural!

Ananda Dasgupta The Numpy Array 27 / 57


Slicing multidimensional arrays

Ananda Dasgupta The Numpy Array 28 / 57


Slicing multidimensional arrays

Ananda Dasgupta The Numpy Array 28 / 57


Slicing multidimensional arrays

Ananda Dasgupta The Numpy Array 28 / 57


Slicing multidimensional arrays

Ananda Dasgupta The Numpy Array 28 / 57


Slicing multidimensional arrays

Ananda Dasgupta The Numpy Array 28 / 57


Slicing multidimensional arrays

Ananda Dasgupta The Numpy Array 28 / 57


Slicing multidimensional arrays

Ananda Dasgupta The Numpy Array 28 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3)

Ananda Dasgupta The Numpy Array 29 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A A[0,:]

Ananda Dasgupta The Numpy Array 29 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A A[0,:] A[1,:]

Ananda Dasgupta The Numpy Array 29 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A A[0,:] A[1,:] A[:,1]

Ananda Dasgupta The Numpy Array 29 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A A[0,:] A[1,:] A[:,1]

(0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3)

A[:2,:2]

Ananda Dasgupta The Numpy Array 29 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A A[0,:] A[1,:] A[:,1]

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A[:2,:2] A[:2,2:]

Ananda Dasgupta The Numpy Array 29 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A A[0,:] A[1,:] A[:,1]

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A[:2,:2] A[:2,2:] A[::2,::2]

Ananda Dasgupta The Numpy Array 29 / 57


Slicing in pictures

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A A[0,:] A[1,:] A[:,1]

(0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3) (0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3) (1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3) (2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3) (3, 0) (3, 1) (3, 2) (3, 3)

A[:2,:2] A[:2,2:] A[::2,::2] A[1::2,1::2]

Ananda Dasgupta The Numpy Array 29 / 57


Fancy indexing

Ananda Dasgupta The Numpy Array 30 / 57


Fancy indexing

Ananda Dasgupta The Numpy Array 30 / 57


Fancy indexing

Ananda Dasgupta The Numpy Array 30 / 57


Fancy indexing

Ananda Dasgupta The Numpy Array 30 / 57


Fancy indexing in pictures

(0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3)

A[:,[0,2]]

Ananda Dasgupta The Numpy Array 31 / 57


Fancy indexing in pictures

(0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3)

A[[1,2],[0,2]]
Will produce 1D array!

Ananda Dasgupta The Numpy Array 31 / 57


Fancy indexing in pictures

(0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3)

A[:,np.array([True,False,False,True])]

Ananda Dasgupta The Numpy Array 31 / 57


Fancy indexing in pictures

(0, 0) (0, 1) (0, 2) (0, 3)

(1, 0) (1, 1) (1, 2) (1, 3)

(2, 0) (2, 1) (2, 2) (2, 3)

(3, 0) (3, 1) (3, 2) (3, 3)

 A[:,B] 
True, False, False, False,
False, True, True, False,
where B =  
False, True, False, True, 
False, False, False, True,
Will produce 1D array!
Ananda Dasgupta The Numpy Array 31 / 57
Reshaping arrays

Elements of an array are stored consecutively in memory.

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Elements of an array are stored consecutively in memory.

The shape attribute of an array is a tuple that determines the


number of elements along each of the axes.

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Elements of an array are stored consecutively in memory.

The shape attribute of an array is a tuple that determines the


number of elements along each of the axes.

It can be set to other values to change this!

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Elements of an array are stored consecutively in memory.

The shape attribute of an array is a tuple that determines the


number of elements along each of the axes.

It can be set to other values to change this!

Changing the shape produces a new view of the array - not a


dierent array!

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Elements of an array are stored consecutively in memory.

The shape attribute of an array is a tuple that determines the


number of elements along each of the axes.

It can be set to other values to change this!

Changing the shape produces a new view of the array - not a


dierent array!

The new shape value must be compatible with the size.

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Elements of an array are stored consecutively in memory.

The shape attribute of an array is a tuple that determines the


number of elements along each of the axes.

It can be set to other values to change this!

Changing the shape produces a new view of the array - not a


dierent array!

The new shape value must be compatible with the size.

An array with shape (24,) can be changed to ones with shapes


(24,1), (1,24), (4,6),(6,4),(12,2),(4,3,2),(2,2,3,2) etc.

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Elements of an array are stored consecutively in memory.

The shape attribute of an array is a tuple that determines the


number of elements along each of the axes.

It can be set to other values to change this!

Changing the shape produces a new view of the array - not a


dierent array!

The new shape value must be compatible with the size.

An array with shape (24,) can be changed to ones with shapes


(24,1), (1,24), (4,6),(6,4),(12,2),(4,3,2),(2,2,3,2) etc.

It can not be changed to (8,4), or (6,3) for example!

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Elements of an array are stored consecutively in memory.

The shape attribute of an array is a tuple that determines the


number of elements along each of the axes.

It can be set to other values to change this!

Changing the shape produces a new view of the array - not a


dierent array!

The new shape value must be compatible with the size.

An array with shape (24,) can be changed to ones with shapes


(24,1), (1,24), (4,6),(6,4),(12,2),(4,3,2),(2,2,3,2) etc.

It can not be changed to (8,4), or (6,3) for example!

The array method reshape() (or the np.reshape() method)


takes a tuple as argument returns a view of the array with this
shape.

Ananda Dasgupta The Numpy Array 32 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 33 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 33 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 34 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 34 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 34 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 34 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 34 / 57


Reshaping arrays

Ananda Dasgupta The Numpy Array 34 / 57


Reshaping arrays
Ravel

np.ravel() or the corresponding array method is a special case of


reshape , returning a 1D view.

Ananda Dasgupta The Numpy Array 35 / 57


Reshaping arrays
Ravel

np.ravel() or the corresponding array method is a special case of


reshape , returning a 1D view.

Ananda Dasgupta The Numpy Array 35 / 57


Reshaping arrays
Ravel

np.ravel() or the corresponding array method is a special case of


reshape , returning a 1D view.

Changing b will change a!

Ananda Dasgupta The Numpy Array 35 / 57


Reshaping arrays
Ravel

np.ravel() or the corresponding array method is a special case of


reshape , returning a 1D view.

Changing b will change a!

Ananda Dasgupta The Numpy Array 35 / 57


Reshaping arrays
Flatten

np.atten() or the corresponding array method returns a 1D copy.

Ananda Dasgupta The Numpy Array 36 / 57


Reshaping arrays
Flatten

np.atten() or the corresponding array method returns a 1D copy.

Ananda Dasgupta The Numpy Array 36 / 57


Reshaping arrays
Flatten

np.atten() or the corresponding array method returns a 1D copy.

Changing c will not change a!

Ananda Dasgupta The Numpy Array 36 / 57


Reshaping arrays
Flatten

np.atten() or the corresponding array method returns a 1D copy.

Changing c will not change a!

Ananda Dasgupta The Numpy Array 36 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

We can use array.shape = (1,4) to make it a row vector.

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

We can use array.shape = (1,4) to make it a row vector.

Or array.shape = (4,1) to make it a column vector.

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

We can use array.shape = (1,4) to make it a row vector.

Or array.shape = (4,1) to make it a column vector.

Reshape can also be used!

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

We can use array.shape = (1,4) to make it a row vector.

Or array.shape = (4,1) to make it a column vector.

Reshape can also be used!

We can also use indexing notation with the np.newaxis


keyword to introduce a new axis, and produce the same result.

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

We can use array.shape = (1,4) to make it a row vector.

Or array.shape = (4,1) to make it a column vector.

Reshape can also be used!

We can also use indexing notation with the np.newaxis


keyword to introduce a new axis, and produce the same result.

array[np.newaxis,:] produces a row vector.

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

We can use array.shape = (1,4) to make it a row vector.

Or array.shape = (4,1) to make it a column vector.

Reshape can also be used!

We can also use indexing notation with the np.newaxis


keyword to introduce a new axis, and produce the same result.

array[np.newaxis,:] produces a row vector.


array[:, np.newaxis] produces a column vector.

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

An 1D array (with, say, 4 elements) has the shape (4,)

We can use array.shape = (1,4) to make it a row vector.

Or array.shape = (4,1) to make it a column vector.

Reshape can also be used!

We can also use indexing notation with the np.newaxis


keyword to introduce a new axis, and produce the same result.

array[np.newaxis,:] produces a row vector.


array[:, np.newaxis] produces a column vector.
The np.newaxis keyword can be used for higher dimensional
arrays as well.

Ananda Dasgupta The Numpy Array 37 / 57


Making row and column vectors out of arrays

Ananda Dasgupta The Numpy Array 38 / 57


Making row and column vectors out of arrays

Ananda Dasgupta The Numpy Array 38 / 57


Making row and column vectors out of arrays

Ananda Dasgupta The Numpy Array 38 / 57


Making row and column vectors out of arrays

Ananda Dasgupta The Numpy Array 38 / 57


Making row and column vectors out of arrays

Ananda Dasgupta The Numpy Array 38 / 57


Stacking arrays
vstack

np.vstack() takes a single iterable as argument and stacks its


pieces vertically!

Ananda Dasgupta The Numpy Array 39 / 57


Stacking arrays
vstack

np.vstack() takes a single iterable as argument and stacks its


pieces vertically!

Ananda Dasgupta The Numpy Array 39 / 57


Stacking arrays
vstack

np.vstack() takes a single iterable as argument and stacks its


pieces vertically!

Ananda Dasgupta The Numpy Array 39 / 57


Stacking arrays
vstack

np.vstack() takes a single iterable as argument and stacks its


pieces vertically!

Ananda Dasgupta The Numpy Array 39 / 57


Stacking arrays
vstack

np.vstack() takes a single iterable as argument and stacks its


pieces vertically!

Ananda Dasgupta The Numpy Array 39 / 57


Stacking arrays
vstack

np.hstack() stacks horizontally!

Ananda Dasgupta The Numpy Array 40 / 57


Stacking arrays
vstack

np.hstack() stacks horizontally!

Ananda Dasgupta The Numpy Array 40 / 57


Stacking arrays
vstack

np.hstack() stacks horizontally!

Ananda Dasgupta The Numpy Array 40 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Leads to less verbose, better maintainable, and


higher-performing code.

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Leads to less verbose, better maintainable, and


higher-performing code.

NumPy implements functions and vectorized operations


corresponding to most fundamental mathematical functions
and operators.

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Leads to less verbose, better maintainable, and


higher-performing code.

NumPy implements functions and vectorized operations


corresponding to most fundamental mathematical functions
and operators.

Most act on arrays on an elementwise basis.

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Leads to less verbose, better maintainable, and


higher-performing code.

NumPy implements functions and vectorized operations


corresponding to most fundamental mathematical functions
and operators.

Most act on arrays on an elementwise basis.


Binary operations require all arrays in an expression to be of
compatible size.

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Leads to less verbose, better maintainable, and


higher-performing code.

NumPy implements functions and vectorized operations


corresponding to most fundamental mathematical functions
and operators.

Most act on arrays on an elementwise basis.


Binary operations require all arrays in an expression to be of
compatible size.
either scalars or

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Leads to less verbose, better maintainable, and


higher-performing code.

NumPy implements functions and vectorized operations


corresponding to most fundamental mathematical functions
and operators.

Most act on arrays on an elementwise basis.


Binary operations require all arrays in an expression to be of
compatible size.
either scalars or
arrays of the same size and shape, or

Ananda Dasgupta The Numpy Array 41 / 57


Putting arrays to use!
Vectorized expressions

The major utility of arrays is the ability to process the data


with concise vectorized expressions,

Batch operations that are applied to all elements!

Ecient use eliminates the need of many explicit for loops.

Leads to less verbose, better maintainable, and


higher-performing code.

NumPy implements functions and vectorized operations


corresponding to most fundamental mathematical functions
and operators.

Most act on arrays on an elementwise basis.


Binary operations require all arrays in an expression to be of
compatible size.
either scalars or
arrays of the same size and shape, or
arrays of such sizes and shapes that can be broadcasted into
each other!
Ananda Dasgupta The Numpy Array 41 / 57
Broadcasting

A scalar is broadcasted over an array by simple repetition!

3 3 1

2 -5 5
+ 1
-1 4 1

1 3 7

Ananda Dasgupta The Numpy Array 42 / 57


Broadcasting

A scalar is broadcasted over an array by simple repetition!

3 3 1 1 1 1

2 -5 5 1 1 1
+
-1 4 1 1 1 1

1 3 7 1 1 1

Ananda Dasgupta The Numpy Array 42 / 57


Broadcasting

A scalar is broadcasted over an array by simple repetition!

4 4 2

3 -4 6

0 5 2

2 4 8

Ananda Dasgupta The Numpy Array 42 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

When can an array be broadcasted into another?

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

When can an array be broadcasted into another?


If the ndims of the two arrays are dierent, the one with the
smaller ndim's shape is padded with enough 1's on the left.

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

When can an array be broadcasted into another?


If the ndims of the two arrays are dierent, the one with the
smaller ndim's shape is padded with enough 1's on the left.
For arrays with the same ndim, either

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

When can an array be broadcasted into another?


If the ndims of the two arrays are dierent, the one with the
smaller ndim's shape is padded with enough 1's on the left.
For arrays with the same ndim, either
Each axis must have equal length, or

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

When can an array be broadcasted into another?


If the ndims of the two arrays are dierent, the one with the
smaller ndim's shape is padded with enough 1's on the left.
For arrays with the same ndim, either
Each axis must have equal length, or
one of them has length 1

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

When can an array be broadcasted into another?


If the ndims of the two arrays are dierent, the one with the
smaller ndim's shape is padded with enough 1's on the left.
For arrays with the same ndim, either
Each axis must have equal length, or
one of them has length 1
The axes with length 1 are repeatedly copied to get the shapes
to match!

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

Binary operations can be carried out element by element on


two arrays with identical shape.

This can be done when the smaller array can be broadcasted


into the shape of the larger array.

When can an array be broadcasted into another?


If the ndims of the two arrays are dierent, the one with the
smaller ndim's shape is padded with enough 1's on the left.
For arrays with the same ndim, either
Each axis must have equal length, or
one of them has length 1
The axes with length 1 are repeatedly copied to get the shapes
to match!

All this happens eciently, behind the scenes!

Ananda Dasgupta The Numpy Array 43 / 57


Broadcasting

A (4,1) array is broadcasted over a (4,3) array by simple repetition!

3 3 1 1

2 -5 5 2
+
-1 4 1 -3

1 3 7 2

Ananda Dasgupta The Numpy Array 44 / 57


Broadcasting

A (4,1) array is broadcasted over a (4,3) array by simple repetition!

3 3 1 1 1 1

2 -5 5 2 2 2
+
-1 4 1 -3 -3 -3

1 3 7 2 2 2

Ananda Dasgupta The Numpy Array 44 / 57


Broadcasting

A (4,1) array is broadcasted over a (4,3) array by simple repetition!

4 4 2

4 -3 7

-4 1 -2

3 5 9

Ananda Dasgupta The Numpy Array 44 / 57


Broadcasting

A (3,) array is reshaped to a (1,3) array and then broadcasted over


a (4,3) array by simple repetition!

3 3 1

2 -5 5
+ 2 -3 2
-1 4 1

1 3 7

Ananda Dasgupta The Numpy Array 45 / 57


Broadcasting

A (3,) array is reshaped to a (1,3) array and then broadcasted over


a (4,3) array by simple repetition!

3 3 1 2 -3 2

2 -5 5 2 -3 2
+
-1 4 1 2 -3 2

1 3 7 2 -3 2

Ananda Dasgupta The Numpy Array 45 / 57


Broadcasting

A (3,) array is reshaped to a (1,3) array and then broadcasted over


a (4,3) array by simple repetition!

5 0 3

4 -8 7

1 1 3

3 0 9

Ananda Dasgupta The Numpy Array 45 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan
np.arccos,np.arcsin, np.arctan

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan
np.arccos,np.arcsin, np.arctan
np.cosh, np.sinh, np.tanh

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan
np.arccos,np.arcsin, np.arctan
np.cosh, np.sinh, np.tanh
np.arccosh,np.arcsinh, np.arctanh

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan
np.arccos,np.arcsin, np.arctan
np.cosh, np.sinh, np.tanh
np.arccosh,np.arcsinh, np.arctanh
np.sqrt

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan
np.arccos,np.arcsin, np.arctan
np.cosh, np.sinh, np.tanh
np.arccosh,np.arcsinh, np.arctanh
np.sqrt
np.exp

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan
np.arccos,np.arcsin, np.arctan
np.cosh, np.sinh, np.tanh
np.arccosh,np.arcsinh, np.arctanh
np.sqrt
np.exp
np.log, np.log2, np.log10

Ananda Dasgupta The Numpy Array 46 / 57


Elementwise functions

Numpy provides several vectorized functions for elementwise


evaluation!
np.cos, np.sin, np.tan
np.arccos,np.arcsin, np.arctan
np.cosh, np.sinh, np.tanh
np.arccosh,np.arcsinh, np.arctanh
np.sqrt
np.exp
np.log, np.log2, np.log10
...

Ananda Dasgupta The Numpy Array 46 / 57


Vectorizing functions

We may need to dene new functions that act on every


element of an array.

Ananda Dasgupta The Numpy Array 47 / 57


Vectorizing functions

We may need to dene new functions that act on every


element of an array.

It is best if we could construct this out of existing numpy


functions.

Ananda Dasgupta The Numpy Array 47 / 57


Vectorizing functions

We may need to dene new functions that act on every


element of an array.

It is best if we could construct this out of existing numpy


functions.

In case this is not possible, we may resort to the


np.vectorize() function!

Ananda Dasgupta The Numpy Array 47 / 57


Vectorizing functions

We may need to dene new functions that act on every


element of an array.

It is best if we could construct this out of existing numpy


functions.

In case this is not possible, we may resort to the


np.vectorize() function!
This gives neater code.

Ananda Dasgupta The Numpy Array 47 / 57


Vectorizing functions

We may need to dene new functions that act on every


element of an array.

It is best if we could construct this out of existing numpy


functions.

In case this is not possible, we may resort to the


np.vectorize() function!
This gives neater code.

It is relatively slower than native numpy though!

Ananda Dasgupta The Numpy Array 47 / 57


Vectorizing functions
A python function dened for a single variable

Ananda Dasgupta The Numpy Array 48 / 57


Vectorizing functions
A python function dened for a single variable can not act on an array!

Ananda Dasgupta The Numpy Array 48 / 57


Vectorizing functions
Vectorizing gives a function that can!

Ananda Dasgupta The Numpy Array 48 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

np.mean

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

np.mean

np.std, np.var

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

np.mean

np.std, np.var

np.cumsum, np.cumprod

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

np.mean

np.std, np.var

np.cumsum, np.cumprod

np.min, np.max

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

np.mean

np.std, np.var

np.cumsum, np.cumprod

np.min, np.max

np.argmin, np.argmax

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

np.mean

np.std, np.var

np.cumsum, np.cumprod

np.min, np.max

np.argmin, np.argmax

np.all, np.any

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Numpy oers several functions for calculating aggregates over


arrays!

np.sum, np.prod

np.mean

np.std, np.var

np.cumsum, np.cumprod

np.min, np.max

np.argmin, np.argmax

np.all, np.any

We can use the keyword argument axis to control the axis over
which the aggregation is carried out!

Ananda Dasgupta The Numpy Array 49 / 57


Aggregate Functions

Ananda Dasgupta The Numpy Array 50 / 57


Operations on Arrays
There are a few operations that act on an array as a whole.

Ananda Dasgupta The Numpy Array 51 / 57


Operations on Arrays
There are a few operations that act on an array as a whole.

Ananda Dasgupta The Numpy Array 51 / 57


Operations on Arrays
There are a few operations that act on an array as a whole.

Ananda Dasgupta The Numpy Array 51 / 57


Operations on Arrays
There are a few operations that act on an array as a whole.

Ananda Dasgupta The Numpy Array 51 / 57


Operations on Arrays
There are a few operations that act on an array as a whole.

Ananda Dasgupta The Numpy Array 51 / 57


Operations on Arrays
There are a few operations that act on an array as a whole.

Ananda Dasgupta The Numpy Array 51 / 57


Matrix and vector operations

Arrays are like matrices, but they are NOT matrices!

Ananda Dasgupta The Numpy Array 52 / 57


Matrix and vector operations

Arrays are like matrices, but they are NOT matrices!

However, math with matrices and vectors are one of the most
common applications of arrays.

Ananda Dasgupta The Numpy Array 52 / 57


Matrix and vector operations

Arrays are like matrices, but they are NOT matrices!

However, math with matrices and vectors are one of the most
common applications of arrays.

Biggest issue : A*B is element by element multiplication - not


matrix multiplication.

Ananda Dasgupta The Numpy Array 52 / 57


Matrix and vector operations

Arrays are like matrices, but they are NOT matrices!

However, math with matrices and vectors are one of the most
common applications of arrays.

Biggest issue : A*B is element by element multiplication - not


matrix multiplication.

Numpy provides the np.dot() method for matrix multiplication.

Ananda Dasgupta The Numpy Array 52 / 57


Matrix and vector operations

Arrays are like matrices, but they are NOT matrices!

However, math with matrices and vectors are one of the most
common applications of arrays.

Biggest issue : A*B is element by element multiplication - not


matrix multiplication.

Numpy provides the np.dot() method for matrix multiplication.

The np.linalg submodule also provides several important methods


for linear algebra, like linalg.inv() and linalg.eig()

Ananda Dasgupta The Numpy Array 52 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 53 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 53 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 53 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 53 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 53 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 53 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 54 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 54 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 54 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 54 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 54 / 57


Matrix operations

Ananda Dasgupta The Numpy Array 54 / 57


Applying all this : Gauss Elimination
Problem : Solve the set of simultaneous equations

x +2y −3z −t =0
−3y +2z +6t = −8
−3x −y +3z +t =0
2x +3y +2z −t = −8

Ananda Dasgupta The Numpy Array 55 / 57


Applying all this : Gauss Elimination
Problem : Solve the set of simultaneous equations

x +2y −3z −t =0
−3y +2z +6t = −8
−3x −y +3z +t =0
2x +3y +2z −t = −8
 
1 +2 −3 −1 0
0
 −3 +2 +6 −8

−3 −1 3 1 0 
2 +3 +2 −1 −8

Ananda Dasgupta The Numpy Array 55 / 57


Applying all this : Gauss Elimination
Problem : Solve the set of simultaneous equations

x +2y −3z −t =0
−3y +2z +6t = −8
−3x −y +3z +t =0
2x +3y +2z −t = −8
   
1 +2 −3 −1 0 1 +2 −3 −1 0
0 −3 +2 +6 −8 0 −3 +2 +6 −8

−3
 −→  
−1 3 1 0  0 5 −6 −2 0 
2 +3 +2 −1 −8 0 −1 8 1 −8

Ananda Dasgupta The Numpy Array 55 / 57


Applying all this : Gauss Elimination
Problem : Solve the set of simultaneous equations

x +2y −3z −t =0
−3y +2z +6t = −8
−3x −y +3z +t =0
2x +3y +2z −t = −8
   
1 +2 −3 −1 0 1 +2 −3 −1 0
0 −3 +2 +6 −8  −→
0 −3 +2 +6 −8

−3
  −→
−1 3 1 0  0 5 −6 −2 0 
2 +3 +2 −1 −8 0 −1 8 1 −8
 
1 +2 −3 −1 0
0 −3 +2 +6 −8 
− 38 8 − 40
 
0 0
3

22 16
0 0
3 −1 − 3

Ananda Dasgupta The Numpy Array 55 / 57


Applying all this : Gauss Elimination
Problem : Solve the set of simultaneous equations

x +2y −3z −t =0
−3y +2z +6t = −8
−3x −y +3z +t =0
2x +3y +2z −t = −8
   
1 +2 −3 −1 0 1 +2 −3 −1 0
0 −3 +2 +6 −8  −→
0 −3 +2 +6 −8

−3
  −→
−1 3 1 0  0 5 −6 −2 0 
2 +3 +2 −1 −8 0 −1 8 1 −8
   
1 +2 −3 −1 0 1 +2 −3 −1 0
0 −3 +2 +6 −8   −→
0 −3 +2 +6 −8 
− 38 8 − 40 − 38 8 − 40
  
0 0 0 0
3 3
 
22 16
0 0
3 −1 − 3 0 0 0 21 −42

Ananda Dasgupta The Numpy Array 55 / 57


Gauss elimination
Dissecting a step

1 2 -3 -1 0

0 -3 2 6 -8

0 5 -6 -2 0

0 -1 8 1 -8

Let's see step no 1 - the second step, in detail.

Ananda Dasgupta The Numpy Array 56 / 57


Gauss elimination
Dissecting a step

1 2 -3 -1 0

0 -3 2 6 -8

0 5 -6 -2 0

0 -1 8 1 -8

The pivot is A(1, 1).

Ananda Dasgupta The Numpy Array 56 / 57


Gauss elimination
Dissecting a step

1 2 -3 -1 0

0 -3 2 6 -8

0 5 -6 -2 0

0 -1 8 1 -8

A(2, 1) A(3, 1)
The multipliers are and
A(1, 1) A(1, 1)

Ananda Dasgupta The Numpy Array 56 / 57


Gauss elimination
Dissecting a step

1 2 -3 -1 0

0 -3 2 6 -8

0 5 -6 -2 0

0 -1 8 1 -8

A(2, 1) A(3, 1)
The multipliers are and
A(1, 1) A(1, 1)
- or the array A[2: ,1]/A[1,1]

Ananda Dasgupta The Numpy Array 56 / 57


Gauss elimination
Dissecting a step

1 2 -3 -1 0

0 -3 2 6 -8

0 5 -6 -2 0

0 -1 8 1 -8

We must subtract np.vstack(A[2: ,1]/A[1,1]) * A[1,1: ]

Ananda Dasgupta The Numpy Array 56 / 57


Gauss elimination
Dissecting a step

1 2 -3 -1 0

0 -3 2 6 -8

0 5 -6 -2 0

0 -1 8 1 -8

We must subtract np.vstack(A[2: ,1]/A[1,1]) * A[1,1: ]


from A[2: ,1: ]

Ananda Dasgupta The Numpy Array 56 / 57


Gauss elimination
Dissecting a step

1 2 -3 -1 0

0 -3 2 6 -8

0 5 -6 -2 0

0 -1 8 1 -8

In the step number i,


we subtract np.vstack(A[i+1: ,i]/A[i,i]) * A[i,i: ]
from A[i+1: ,i: ]

Ananda Dasgupta The Numpy Array 56 / 57


Gauss elimination
The Program

Ananda Dasgupta The Numpy Array 57 / 57


Gauss elimination
The Program

Ananda Dasgupta The Numpy Array 57 / 57

You might also like