100% found this document useful (1 vote)
191 views

NumPy Arrays Notes

The document provides an overview of NumPy concepts and functions used for scientific computing in Python. It introduces NumPy arrays as n-dimensional containers for numeric data and describes how to define, slice, index and perform basic operations on arrays. Functions covered include zeros, ones, empty, array, transpose, linspace, logspace, meshgrid, arange and enumerate. The document is intended as a tutorial for researchers to learn the essential NumPy library for working with multi-dimensional data in Python.

Uploaded by

Gab Miro
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
191 views

NumPy Arrays Notes

The document provides an overview of NumPy concepts and functions used for scientific computing in Python. It introduces NumPy arrays as n-dimensional containers for numeric data and describes how to define, slice, index and perform basic operations on arrays. Functions covered include zeros, ones, empty, array, transpose, linspace, logspace, meshgrid, arange and enumerate. The document is intended as a tutorial for researchers to learn the essential NumPy library for working with multi-dimensional data in Python.

Uploaded by

Gab Miro
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Week 2:

Python Libraries
and Concepts Used
in Research
PART 2: NUMPY

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 1


2.2.1:
INTRODUCTION TO NUMPY ARRAYS

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 2


NumPy Arrays
NumPy arrays
n-dimensional array objects
represent vectors and matrices
fixed size when created
elements are of the same data type
by default, numbers are represented as floating point values

Importing NumPy
import numpy as np

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 3


Defining NumPy Arrays
Array of zeros
np.zeros()

In [1]: np.zeros(5)
Out [1]: array([0., 0., 0., 0., 0.])

In [2]: np.zeros((5,3))
Out [2]: array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 4


Defining NumPy Arrays
Array of ones
np.ones()

Empty array
np.empty()
does not initialize array
recommended for very large arrays where each element will be updated

Array with specified values


np.array()
np.array([1, 2, 3])
np.array([[1, 3], [5, 9]])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 5


transpose Function
Transpose of a matrix
np_array.transpose()
rows will become columns, vice versa

In [1]: A = np.array([[1, 3], [5, 9]])


In [2]: A.transpose()
Out [2]: array([[1, 5],
[3, 9]])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 6


2.2.2:
SLICING NUMPY ARRAYS

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 7


Indices of NumPy Arrays
1D NumPy arrays
like lists, index starts at 0

2D NumPy arrays
First index row
Second index - column

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 8


Slicing NumPy Arrays
1D NumPy arrays
np_array[start:end]
inclusive of start, exclusive of end

2D NumPy arrays
np_array[:,j]
jth column of np_array

np_array[i,:] or np_array[i]
ith row of np_array

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 9


2.2.3:
INDEXING NUMPY ARRAYS

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 10


Sequence-like Indices
NumPy arrays can be indexed with other arrays or other sequence-like
objects like list (or arrays)
In [1]: z1 = np.array([1,3,5,7,9])

In [2]: z2 = z1 + 1

In [3]: z1
Out [3]: array([1, 3, 5, 7, 9])
In [4]: z2
Out [4]: array([ 2, 4, 6, 8, 10])
In [5]: ind = [0,2,3]

In [6]: z1[ind]
Out [6]: array([1, 5, 7])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 11


Logical Indices
NumPy arrays can also be indexed using logical indices
In [1]: z1 = np.array([1,3,5,7,9])

In [2]: z1 > 6
Out [2]: array([False, False, False, True, True], dtype=bool)
In [3]: z1[z1 > 6]
Out [3]: array([7, 9])
In [5]: ind = z1 > 6

In [6]: ind
Out [6]: array([False, False, False, True, True], dtype=bool
In [7]: z1[ind]
Out [7]: array([7, 9])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 12


Slicing versus Indexing
Slicing an array using the colon operator returns a view of the object.
Modifying this view will also modify the original array.
Indexing an array returns a copy of the original data.
In [1]: w = z1[0:3]

In [2]: w
Out [2]: array([1, 3, 5])
In [3]: w[0] = 3

In [4]: w
Out [4]: array([3, 3, 5])
In [5]: z1
Out [5]: array([3, 3, 5, 7, 9])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 13


Slicing versus Indexing
Indexing an array returns a copy of the original data.
In [1]: ind = np.array([0,1,2])

In [2]: w = z1[ind]

In [3]: w
Out [3]: array([1, 3, 5])
In [4]: w[0] = 3

In [5]: w
Out [5]: array([3, 3, 5])
In [6]: z1
Out [6]: array([1, 3, 5, 7, 9])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 14


2.2.4:
BUILDING AND EXAMINING NUMPY ARRAYS

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 15


linspace Function
Initializes and constructs an array of linearly spaced elements
np.linspace[start, end, step]
constructs an array from start to end, inclusive, with step number of
elements
In [1]: np.linspace(0, 100, 11)
Out [1]: array([ 0., 10., 20., 30., 40., 50., 60.,
70., 80., 90., 100.,])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 16


logspace Function
Initializes and constructs an array of logarithmically spaced elements
np.logspace[log10(start), log10(end), step]
constructs an array from start to end, inclusive, with step number of
elements
In [1]: np.linspace(0, 100, 11)
Out [1]: array([ 10. , 12.91549665, 16.68100537,
21.5443469 , 27.82559402, 35.93813664,
46.41588834, 59.94842503, 77.42636827,
100. ])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 17


shape and size Attributes
Returns the shape of the array, i.e. number of rows and/or columns
np_array.shape

Returns the size of the array, i.e. number of elements


np_array.size
In [1]: X = np.array([[1,2,3], [4,5,6]])

In [2]: X.shape
Out [2]: (2, 3)
In [3]: X.size
Out [3]: 6

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 18


any and all Functions
Returns a bool if any of the elements of the array fulfills the given
condition
np.any(condition)

Returns a bool if all of the elements of the array fulfills the given
condition
np.all(condition)
In [1]: x = np.array(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)

In [2]: np.any(x > 0.9)


Out [2]: True
In [3]: np.all(x >= 0.1)
Out [3]: True

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 19


[2.2.4]:
BASIC OPERATIONS
NUMPY USER GUIDE 1.13.0

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 20


Arithmetic Operations
Arithmetic operators on arrays apply elementwise
A new array is created and filled with the result
The product operator, *, operates elementwise
Matrix product can be performed using the dot function or method
np.dot(array1, array2)
array1.dot(array2)

Some operations, such as += and *=, act in place to modify an existing


array rather than create a new one
When operating with arrays of different types, the type of the
resulting array corresponds to the more general or precise one (a
behavior known as upcasting)

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 21


Unary Operations
Many unary operations are implemented as methods of the ndarray
class
By default, these operations apply to the array as though it were a list
of numbers, regardless of its shape
However, by specifying the axis parameter you can apply an
operation along the specified axis of an array

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 22


Unary Operations
>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>>
>>> b.sum(axis=0) # sum of each column
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1) # min of each row
array([0, 4, 8])
>>>
>>> b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38]])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 23


3.3.6:
MAKING A PREDICTION GRID

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 24


meshgrid Function
Returns coordinate matrices from coordinate vectors
np.meshgrid(x1, x2, ..., xi)

In [1]:
x1 = np.array([0,1,2]); x2 = np.array([3,4,5])
In [2]:
x, y = np.meshgrid(x1, x2)
In [3]:
x
Out [3]:
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2]])
In [4]: y
Out [4]: array([[3, 3, 3],
[4, 4, 4],
[5, 5, 5]])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 25


arange Function
Returns evenly spaced values within a given interval
np.arange(start, stop, step)
similar to range() function, only stop is required argument
(optional kwarg) dtype specify type of return values

In [1]: x = np.arange(0,10,2)
Out [1]: array([0, 2, 4, 6, 8])

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 26


enumerate Function
Returns an enumerate object, a tuple containing a count and the
values obtained from iterating over the input sequence
enumerate(sequence, start=0)
sequence must be a sequence, an iterator, or some iterable object

In [1]: seasons = ['Spring', 'Summer', 'Fall', 'Winter']


In [2]: list(enumerate(seasons))
Out [2]:[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'),
(3,'Winter')]
In [3]: list(enumerate(seasons, start=1))
Out [3]: [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'),
(4, 'Winter')]

Week 2 | Part 2 PH526X | USING PYTHON FOR RESEARCH 27

You might also like