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

Indexing with a list of locations


Let's use the ix_() function to shuffle the Lena image. This function creates a mesh from multiple sequences.

How to do it...

We will start by randomly shuffling the array indices:

  1. Create a random indices array with the shuffle() function of the numpy.random module:

    def shuffle_indices(size):
       arr = np.arange(size)
       np.random.shuffle(arr)
    
       return arr
  2. Plot the shuffled indices:

    plt.imshow(lena[np.ix_(xindices, yindices)])
    

    What we get is a completely scrambled Lena image, as shown in the following screenshot:

    Here is the complete code for the recipe from the ix.py file in this book's code bundle:

    import scipy.misc
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Load the Lena array
    lena = scipy.misc.lena()
    xmax = lena.shape[0]
    ymax = lena.shape[1]
    
    def shuffle_indices(size):
       '''
       Shuffles an array with values 0 - size
       '''
       arr = np.arange(size)
       np.random.shuffle(arr)
    
       return arr
    
    xindices = shuffle_indices(xmax)
    np.testing.assert_equal...