Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
NumPy Cookbook
NumPy Cookbook

NumPy Cookbook: If you're a Python developer with basic NumPy skills, the 70+ recipes in this brilliant cookbook will boost your skills in no time. Learn to raise productivity levels and code faster and cleaner with the open source mathematical library.

eBook
£19.99 £28.99
Paperback
£37.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

NumPy Cookbook

Chapter 2. Advanced Indexing and Array Concepts

In this chapter, we will cover:

  • Installing SciPy

  • Installing PIL

  • Resizing images

  • Comparing views and copies

  • Flipping Lena

  • Fancy indexing

  • Indexing with a list of locations

  • Indexing with booleans

  • Stride tricks for Sudoku

  • Broadcasting arrays

Introduction


NumPy is famous for its efficient arrays. This fame is partly due to the ease of indexing. We will demonstrate advanced indexing tricks using images. Before diving into indexing, we will install the necessary software— SciPy and PIL.

Note

The code for the recipes in this chapter can be found on the book website at http://www.packtpub.com. You can also visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Some of the examples in this chapter will involve manipulating images. In order to do that, we will require the Python Image Library (PIL) ; but don't worry, instructions and pointers to help you install PIL and other necessary Python software are given throughout the chapter, when necessary.

Installing SciPy


SciPy is the scientific Python library and is closely related to NumPy. In fact, SciPy and NumPy used to be one and the same project many years ago. In this recipe, we will install SciPy.

Getting ready

In Chapter 1, Winding Along with IPython, we discussed how to install setup tools and pip. Reread the recipe if necessary.

How to do it...

In this recipe, we will go through the steps for installing SciPy.

  • Installing from source: If you have Git installed, you can clone the SciPy repository using the following command:

    git clone https://github.com/scipy/scipy.git
    
    python setup.py build
    python setup.py install --user   
    

    This installs to your home directory and requires Python 2.6 or higher.

    Before building, you will also need to install the following packages on which SciPy depends:

    • BLAS and LAPACK libraries

    • C and Fortran compilers

    There is a chance that you have already installed this software as a part of the NumPy installation.

  • Installing SciPy on Linux: Most Linux distributions...

Installing PIL


PIL, the Python imaging library, is a prerequisite for the image processing recipes in this chapter.

How to do it...

Let's see how to install PIL.

  • Installing PIL on Windows: Install using the Windows executable from the PIL website http://www.pythonware.com/products/pil/.

  • Installing on Debian or Ubuntu: On Debian or Ubuntu, install PIL using the following command:

    sudo apt-get install python-imaging
    
  • Installing with easy_install or pip: At the time of writing this book, it appeared that the package managers of Red Hat, Fedora, and CentOS did not have direct support for PIL. Therefore, please follow this step if you are using one of these Linux distributions.

    Install with either of the following commands:

    easy_install PIL
    sudo pip install PIL
    

Resizing images


In this recipe, we will load a sample image of Lena, which is available in the SciPy distribution, into an array. This chapter is not about image manipulation, by the way; we will just use the image data as an input.

Note

Lena Soderberg appeared in a 1972 Playboy magazine. For historical reasons, one of those images is often used in the field of image processing. Don't worry; the picture in question is completely safe for work.

We will resize the image using the repeat function. This function repeats an array, which in practice means resizing the image by a certain factor.

Getting ready

A prerequisite for this recipe is to have SciPy, Matplotlib, and PIL installed. Have a look at the corresponding recipes in this chapter and the previous chapter.

How to do it...

  1. Load the Lena image into an array.

    SciPy has a lena function, which can load the image into a NumPy array:

    lena = scipy.misc.lena()

    Some refactoring has occurred since version 0.10, so if you are using an older version, the...

Creating views and copies


It is important to know when we are dealing with a shared array view, and when we have a copy of the array data. A slice, for instance, will create a view. This means that if you assign the slice to a variable and then change the underlying array, the value of this variable will change. We will create an array from the famous Lena image, copy the array, create a view, and, at the end, modify the view.

Getting ready

The prerequisites are the same as in the previous recipe.

How to do it...

Let's create a copy and views of the Lena array:

  1. Create a copy of the Lena array:

    acopy = lena.copy()
  2. Create a view of the array:

    aview = lena.view()
  3. Set all the values of the view to 0 with a flat iterator:

    aview.flat = 0

The end result is that only one of the images shows the Playboy model. The other ones get censored completely:

The following is the code of this tutorial showing the behavior of array views and copies:

import scipy.misc
import matplotlib.pyplot

lena = scipy.misc.lena()
acopy...

Flipping Lena


We will be flipping the SciPy Lena image—all in the name of science, of course, or at least as a demo. In addition to flipping the image, we will slice it and apply a mask to it.

How to do it...

The steps to follow are listed below:

  1. Plot the flipped image.

    Flip the Lena array around the vertical axis using the following code:

    matplotlib.pyplot.imshow(lena[:,::-1])
  2. Plot a slice of the image.

    Take a slice out of the image and plot it. In this step, we will have a look at the shape of the Lena array. The shape is a tuple representing the dimensions of the array. The following code effectively selects the left-upper quadrant of the Playboy picture.

    matplotlib.pyplot.imshow(lena[:lena.shape[0]/2,:lena.shape[1]/2])
  3. Apply a mask to the image.

    Apply a mask to the image by finding all the values in the Lena array that are even (this is just arbitrary for demo purposes). Copy the array and change the even values to 0. This has the effect of putting lots of blue dots (dark spots if you are looking...

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 through, 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, which 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 crossed off, as shown in the following screenshot:

The following is the complete code for this recipe:

import scipy.misc
import matplotlib.pyplot

# This script demonstrates fancy...

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. Shuffle array indices.

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

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

    matplotlib.pyplot.imshow(lena[numpy.ix_(xindices, yindices)])

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

The following is the complete code for the recipe:

import scipy.misc
import matplotlib.pyplot
import numpy.random
import numpy.testing

# Load the Lena array
lena = scipy.misc.lena()
xmax = lena.shape[0]
ymax = lena.shape[1]

def shuffle_indices(size):
   arr = numpy.arange(size)
   numpy.random.shuffle(arr)

   return arr
xindices = shuffle_indices(xmax)
numpy.testing.assert_equal(len(xindices), xmax)
yindices...

Indexing with booleans


Boolean indexing is indexing based on a boolean array and falls in the category fancy indexing.

How to do it...

We will apply this indexing technique to an image:

  1. Image with dots on the diagonal.

    This is in some way similar to the Fancy indexing recipe, in this chapter. This time we select modulo 4 points on the diagonal of the image:

    def get_indices(size):
       arr = numpy.arange(size)
       return arr % 4 == 0

    Then we just apply this selection and plot the points:

    lena1 = lena.copy() 
    xindices = get_indices(lena.shape[0])
    yindices = get_indices(lena.shape[1])
    lena1[xindices, yindices] = 0
    matplotlib.pyplot.subplot(211)
    matplotlib.pyplot.imshow(lena1)
  2. Set to 0 based on value.

    Select array values between quarter and three-quarters of the maximum value and set them to 0:

    lena2[(lena > lena.max()/4) & (lena < 3 * lena.max()/4)] = 0

The plot with the two new images will look like the following screenshot:

The following is the complete code for this recipe:

import scipy.misc...

Stride tricks for Sudoku


The ndarray class has a strides field, which is a tuple indicating the number of bytes to step in each dimension when going through an array. Let's apply some stride tricks to the problem of splitting a Sudoku puzzle to the 3 by 3 squares of which it is composed.

Note

Explaining the Sudoku rules is outside the scope of this book. For more information see http://en.wikipedia.org/wiki/Sudoku.

How to do it...

  1. Define the Sudoku puzzle array

    Let's define the Sudoku puzzle array. This one is filled with the contents of an actual, solved Sudoku puzzle:

    sudoku = numpy.array([
        [2, 8, 7, 1, 6, 5, 9, 4, 3],
        [9, 5, 4, 7, 3, 2, 1, 6, 8],
        [6, 1, 3, 8, 4, 9, 7, 5, 2],
        [8, 7, 9, 6, 5, 1, 2, 3, 4],
        [4, 2, 1, 3, 9, 8, 6, 7, 5],
        [3, 6, 5, 4, 2, 7, 8, 9, 1],
        [1, 9, 8, 5, 7, 3, 4, 2, 6],
        [5, 4, 2, 9, 1, 6, 3, 8, 7],
        [7, 3, 6, 2, 8, 4, 5, 1, 9]
        ])
  2. Calculate the strides. The itemsize field of ndarray gives us the number of bytes in an array. Using the...

Broadcasting arrays


Without knowing it, you might have broadcasted arrays. In a nutshell, NumPy tries to perform an operation even though the operands do not have the same shape. In this recipe, we will multiply an array and a scalar. The scalar is "extended" to the shape of the array operand and then the multiplication is performed. We will download an audio file and make a new version that is quieter.

How to do it...

Let's start by reading a WAV file:

  1. Reading a WAV file.

    We will use a standard Python code to download an audio file of Austin Powers called "Smashing, baby". SciPy has a wavfile module, which allows you to load sound data or generate WAV files. If SciPy is installed, then we should have this module already. The read function returns a data array and sample rate. In this example, we only care about the data:

    sample_rate, data = scipy.io.wavfile.read(WAV_FILE)
  2. Plot the original WAV data.

    Plot the original WAV data with Matplotlib. Give the subplot the title Original.

    matplotlib.pyplot...
Left arrow icon Right arrow icon

Key benefits

  • Do high performance calculations with clean and efficient NumPy code
  • Analyze large sets of data with statistical functions
  • Execute complex linear algebra and mathematical computations

Description

Today's world of science and technology is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy will give you both speed and high productivity. "NumPy Cookbook" will teach you all about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, it is free and open source. "Numpy Cookbook" will teach you to write readable, efficient, and fast code that is as close to the language of Mathematics as much as possible with the cutting edge open source NumPy software library. You will learn about installing and using NumPy and related concepts. At the end of the book, we will explore related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project through examples. "NumPy Cookbook" will help you to be productive with NumPy and write clean and fast code.

Who is this book for?

This book will take Python developers with basic Numpy skills to the next level through some practical recipes.

What you will learn

  • Learn advanced Indexing and linear algebra
  • Know reshaping automatically
  • Dive into Broadcasting and Histograms
  • Profile NumPy code and visualize your profiling results
  • Speed up your code with Cython
  • Use the array interface to expose foreign memory to NumPy
  • Use universal functions and interoperability features
  • Learn about Matplotlib and Scipy which is often used in conjunction with Numpy

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 25, 2012
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781849518932
Category :
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Oct 25, 2012
Length: 226 pages
Edition : 1st
Language : English
ISBN-13 : 9781849518932
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 117.97
NumPy Beginner's Guide
£37.99
Building Machine Learning Systems with Python
£41.99
NumPy Cookbook
£37.99
Total £ 117.97 Stars icon

Table of Contents

10 Chapters
Winding Along with IPython Chevron down icon Chevron up icon
Advanced Indexing and Array Concepts Chevron down icon Chevron up icon
Get to Grips with Commonly Used Functions Chevron down icon Chevron up icon
Connecting NumPy with the Rest of the World Chevron down icon Chevron up icon
Audio and Image Processing Chevron down icon Chevron up icon
Special Arrays and Universal Functions Chevron down icon Chevron up icon
Profiling and Debugging Chevron down icon Chevron up icon
Quality Assurance Chevron down icon Chevron up icon
Speed Up Code with Cython Chevron down icon Chevron up icon
Fun with Scikits Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(17 Ratings)
5 star 29.4%
4 star 52.9%
3 star 5.9%
2 star 11.8%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Sujit Pal Jun 22, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Numpy is central to most scientific Python toolkits, and learning to write effective Numpy code can make your code more readable and faster. While the Numpy documentation is quite comprehensive, books provide a more structured learning path, and since there are not too many books on Numpy, this book hits a sweet spot. The book is aimed at intermediate level Python users. You will gain more from the book if you work out the code examples yourself rather than just read the examples. Also the examples are slightly mathy (its a book about arrays and matrices after all), so you may have to do some reading if you don't remember your linear algebra, for example.The book covers examples from famous algorithms (Fibonacci, Sieve of Eratosthenes, etc), finance, etc, mainly to show the usage for various NumPy functions, both simple and advanced. There is a full chapter of recipes on Audio and Image processing techniques. There is also discussion of using memory mapped files, sharing data with the Python Image Library (PIL) through the array interface, converting code to Cython for speed, universal functions (none on vectorize() strangely), masking, etc. There is other information, such as interfacing with R using RPy2, running Numpy on Google App Engine and PiCloud (I didn't pay too much attention to these since I didn't anticipate using them).The format of the recipes were a bit unusual. Generally it tells you what you can do with it (in the title), then gives a quick overview of the approach (in English), followed by the full code to do accomplish the recipe. The recipes in the book flips this around, putting partial code with some explanation first, then the full code, and then the overview. So the reading (or following along with a Python shell) is not linear, reader has to jump back and forth. Not a huge deal once you recognize it, but using a more linear style may enhance the reading and learning experience in future editions.I read this book after I read "Learning Numpy Arrays" by the same author, and there is quite a bit of overlap in the examples. Perhaps not surprising because the subject is mostly identical. However, I think its still worth purchasing both the books because each book has enough unique content.
Amazon Verified review Amazon
Tom Jensen Morgan Jan 15, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I read this book during the holidays. [...] I found it quite useful and well-written. I am just learning Python and am primarily interested in how it can be used for geospatial processing. I recommend this book for anyone wanting to grow their Python skillset.
Amazon Verified review Amazon
BeckyLEXI Jan 30, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
While this book has some advanced examples, the nice thing is that it is accessible for newer to intermediate users of python and NumPy. The recipes are well documented and are concrete, helping with the learning experience. The range of the examples also helps to expand your understanding of what NumPy is capable of - which is enlightening. I will continue to use this book as a reference into the future.
Amazon Verified review Amazon
Amazon Customer Dec 28, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
When I first mentioned that I was getting this book, a colleague of mine wanted to know why I was even bothering - 'just go straight for Pandas' he said. Actually, I think he is missing the point of both this book and NumPy in general.Not only is this one of those well written cookbooks that sets out the problems and solutions neatly and succinctly, but it is one of those cookbooks that you turn to, not really expecting to find the answer to a problem you are having right now, but rather solutions to problems that give you insight into just how broad and wide the solutions that NumPy can be applied to.The NumPy Cookbook covers everything from getting started with IPython (worth the price of admission alone, trust me) - to re-sizing images, processing audio, performing statistical analysis (obviously), estimating stock returns and, well, err, installing Pandas.The very best cookbooks answer the questions you did not know you had, and show you to do things that you did not know were possible. That is what the 'NumPy Cookbook' does - and it does it exceptionally well.I spend my time working with Python, examining numbers from our data warehouse, and I have been using NumPy for a long while to manipulate the data, to slice, dice and fill in the blanks. But this book showed me some new tricks, some tricks that I will be able to apply directly to my work, and for that I am grateful.So, install Pandas and forget all about NumPy? No. NumPy is a pre-requisite for Pandas, and you really should know all about it, because the two are not mutually exclusive. Read this book - and learn about some of the really cool stuff that you can do with NumPy.
Amazon Verified review Amazon
alan1955 Jan 15, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am a scientist just beginning to use Python, Numpy, Scipy, and Matplotlib on a Linux machine. There are a lot of things to learn to use with anyone of these. This book provides valuable insights for a person just beginning with Numpy that would take a long time to discover on your own through working examples. The examples are quite extensive covering many areas. All areas are not of interest to me, but the techniques used through working example can be easily adapted to whatever problem you are working on, saving a lot of time. I would say for me the examples in chapter 7 on Profiling and debugging chapter 2 on advanced indexing, and chapter 3 on commonly used functions were very useful. I would recommend this to anyone who is wanting to get started with Numpy and is planning to use it regularly. More information can be had at: [...]
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.