Book Image

NumPy Essentials

By : Leo (Liang-Huan) Chin, Tanmay Dutta, Shane Holloway
Book Image

NumPy Essentials

By: Leo (Liang-Huan) Chin, Tanmay Dutta, Shane Holloway

Overview of this book

In today’s world of science and technology, it’s all about speed and flexibility. When it comes to scientific computing, NumPy tops the list. NumPy gives you both the speed and high productivity you need. This book will walk you through NumPy using clear, step-by-step examples and just the right amount of theory. We will guide you through wider applications of NumPy in scientific computing and will then focus on the fundamentals of NumPy, including array objects, functions, and matrices, each of them explained with practical examples. You will then learn about different NumPy modules while performing mathematical operations such as calculating the Fourier Transform; solving linear systems of equations, interpolation, extrapolation, regression, and curve fitting; and evaluating integrals and derivatives. We will also introduce you to using Cython with NumPy arrays and writing extension modules for NumPy code using the C API. This book will give you exposure to the vast NumPy library and help you build efficient, high-speed programs using a wide range of mathematical features.
Table of Contents (16 chapters)
NumPy Essentials
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface

A boolean mask


Indexing and slicing are quite handy and powerful in NumPy, but with the booling mask it gets even better! Let's start by creating a boolean array first. Note that there is a special kind of array in NumPy named a masked array. Here, we are not talking about it but we're also going to explain how to extend indexing and slicing with NumPy Arrays:

In [58]: x = np.array([1,3,-1, 5, 7, -1]) 
In [59]: mask = (x < 0) 
In [60]: mask 
Out[60]: array([False, False,  True, False, False,  True], dtype=bool) 

We can see from the preceding example that by applying the < logic sign that we applied scalars to a NumPy Array and the naming of a new array to mask, it's still vectorized and returns the True/False boolean with the same shape of the variable x indicated which element in x meet the criteria:

In [61]: x [mask] = 0 
In [62]: x 
Out[62]: array([1, 3, 0, 5, 7, 0]) 

Using the mask, we gain the ability to access or replace any element value in our...