Book Image

NumPy Cookbook - Second Edition

By : Ivan Idris
Book Image

NumPy Cookbook - Second Edition

By: Ivan Idris

Overview of this book

<p>NumPy has the ability to give you speed and high productivity. High performance calculations can be done easily with clean and efficient code, and it allows you to execute complex algebraic and mathematical computations in no time.</p> <p>This book will give you a solid foundation in NumPy arrays and universal functions. Starting with the installation and configuration of IPython, you'll learn about advanced indexing and array concepts along with commonly used yet effective functions. You will then cover practical concepts such as image processing, special arrays, and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project with the help of examples. At the end of the book, you will study how to explore atmospheric pressure and its related techniques. By the time you finish this book, you'll be able to write clean and fast code with NumPy.</p>
Table of Contents (19 chapters)
NumPy Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Fancy indexing


In this tutorial, we will apply fancy indexing to set the diagonal values of the Lena image to 0. This will draw black lines along the diagonals, crossing it, not because there is something wrong with the image but just as an exercise. Fancy indexing is indexing that does not involve integers or slices; it is normal indexing.

How to do it...

We will start with the first diagonal:

  1. Set the values of the first diagonal to 0.

    To set the diagonal values to 0, we need to define two different ranges for the x and y values:

    lena[range(xmax), range(ymax)] = 0
    
  2. Set the values of the other diagonal to 0.

    To set the values of the other diagonal, we require a different set of ranges, but the principles stay the same:

    lena[range(xmax-1,-1,-1), range(ymax)] = 0
    

    At the end, we get this image with the diagonals marked, as shown in the following screenshot:

    The following is the complete code for this recipe from the fancy.py file in this book's code bundle:

    import scipy.misc
    import matplotlib.pyplot...