Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning SciPy for Numerical and Scientific Computing Second Edition
Learning SciPy for Numerical and Scientific Computing Second Edition

Learning SciPy for Numerical and Scientific Computing Second Edition: Quick solutions to complex numerical problems in physics, applied mathematics, and science with SciPy , Second Edition

eBook
$13.98 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning SciPy for Numerical and Scientific Computing Second Edition

Chapter 2. Working with the NumPy Array As a First Step to SciPy

At the top level, SciPy is basically NumPy, since both the object creation and basic manipulation of these objects are performed by functions of the latter library. This assures much faster computations, since the memory handling is done internally in an optimal way. For instance, if an operation must be made on the elements of a big multidimensional array, a novice user might be tempted to go over columns and rows with as many for loops as necessary. Loops run much faster when they access each consecutive element in the same order in which they are stored in memory. We should not be bothered with considerations of this kind when coding. The NumPy/SciPy operations assure that this is the case. As an added advantage, the names of operations in NumPy/SciPy are intuitive and self explanatory. Code written in this fashion is extremely easy to understand and maintain, faster to correct or change in case of need.

Let&apos...

Object essentials

We have been introduced to NumPy's main object—the homogeneous multidimensional array, also referred to as ndarray. All elements of the array are casted to the same datatype (homogeneous). We obtain the datatype by the dtype attribute, its dimension by the shape attribute, the total number of elements in the array by the size attribute, and elements by referring to their positions:

>>> img.dtype, img.shape, img.size

The output is shown as follows:

(dtype('int64'), (512, 512), 262144)

Let's compute the grayscale values now:

>>> img[32,67]

The output is shown as follows:

87

Let's interpret the outputs. The elements of img are 64-bit integer values ('int64'). This may vary depending on the system, the Python installation, and the computer specifications. The shape of the array (note it comes as a Python tuple) is 512 x 512, and the number of elements 262144. The grayscale value of the image in the 33rd column and 68...

Using datatypes

There are several approaches to impose the datatype. For instance, if we want all entries of an already created array to be 32-bit floating point values, we may cast it as follows:

>>> import scipy.misc
>>> img=scipy.misc.lena().astype('float32')

We can also use an optional argument, dtype through the command:

>>> import numpy
>>> scores = numpy.array([101,103,84], dtype='float32')
>>> scores

The output is shown as follows:

array([ 101.,  103.,   84.], dtype=float32)

This can be simplified even further with a third clever method (although this practice offers code that are not so easy to interpret):

>>> scores = numpy.float32([101,103,84])
>>> scores

The output is shown as follows:

array([ 101.,  103.,   84.], dtype=float32)

The choice of datatypes for NumPy arrays is very flexible; we may choose the basic Python types (including bool, dict, list, set, tuple, str, and unicode), although for numerical...

Indexing and slicing arrays

There are two basic methods to access the data in a NumPy array; let's call that array for A. Both methods use the same syntax, A[obj], where obj is a Python object that performs the selection. We are already familiar with the first method of accessing a single element. The second method is the subject of this section, namely slicing. This concept is exactly what makes NumPy and SciPy so incredibly easy to manage.

The basic slice method is a Python object of the form slice(start,stop,step), or in a more compact notation, start:stop:step. Initially, the three variables, start, stop, and step are non-negative integer values, with start less than or equal to stop.

This represents the sequence of indices k = start + (i * step), where k runs from start to the largest integer k_max = start + step*int((stop-start)/step), or i from 0 to the largest integer equal to int((stop - start) / step). When a slice method is invoked on any of the dimensions of ndarray, it...

The array object

At this point, we are ready for a thorough study of all interesting attributes of ndarray for scientific computing purposes. We have already covered a few, such as dtype, shape, and size. Other useful attributes are ndim (to compute the number of dimensions in the array), real, and imag (to obtain the real and imaginary parts of the data, should this be formed by complex numbers) or flat (which creates a one-dimensional indexable iterator from the data).

For instance, if we desired to add all the values of an array together, we could use the flat attribute to run over all the elements sequentially, and accumulate all the values in a variable. A possible code to perform this task should look like the following code snippet (compare this code with the ndarray.sum() method, which will be explained in object calculation ahead):

>>> value=0; import scipy.misc; img=scipy.misc.lena()
>>> for item in img.flat: value+=item
>>> value

The output is shown as...

Array routines

In this section, we will deal with most operations on arrays. We will classify them into four main categories:

  • Routines to create new arrays
  • Routines to manipulate a single array
  • Routines to combine two or more arrays
  • Routines to extract information from arrays

The reader will surely realize that some operations of this kind can be carried out by methods, which once again shows the flexibility of Python and NumPy.

Routines to create arrays

We have previously seen the command to create an array and store it to a variable A. Let's take a look at it again:

>>> A=numpy.array([[1,2],[2,1]])

The complete syntax, however, writes as follows:

array(object,dtype=None,copy=True,order=None, subok=False,ndim=0)

Let's go over the options: object is simply the data we use to initialize the array. In the previous example, the object is a 2 x 2 square matrix; we may impose a datatype with the dtype option. The result is stored in the variable A. If copy is True, the returned object...

Summary

In this chapter, we have explored in depth the creation and basic manipulation of the object array used by SciPy, as an overview of the NumPy libraries. In particular, we have seen the principles of slicing and masking, which simplify the coding of algorithms to the point of transforming an otherwise unreadable sequence of loops and primitive commands into an intuitive and self-explanatory set of object calls and methods. You also learned that the nonbasic modules in NumPy are replicated as modules in SciPy itself. The chapter roughly followed the same structure as the official NumPy reference (which the reader can access at the SciPy pages http://docs.scipy.org/doc/numpy/reference/). There are other good sources that cover NumPy with rigor, and we refer you to any of that material for a more detailed coverage of this topic.

In the next five chapters, we will be accessing the commands that make SciPy a powerful tool in numerical computing. The structure of those chapters is basically...

Left arrow icon Right arrow icon

Description

This book targets programmers and scientists who have basic Python knowledge and who are keen to perform scientific and numerical computations with SciPy.

Who is this book for?

This book targets programmers and scientists who have basic Python knowledge and who are keen to perform scientific and numerical computations with SciPy.

What you will learn

  • Get to know the benefits of using the combination of Python, NumPy, SciPy, and matplotlib as a programming environment for scientific purposes
  • Create and manipulate an object array used by SciPy
  • Use SciPy with large matrices to compute eigenvalues and eigenvectors
  • Focus on construction, acquisition, quality improvement, compression, and feature extraction of signals
  • Make use of SciPy to collect, organize, analyze, and interpret data, with examples taken from statistics and clustering
  • Acquire the skill of constructing a triangulation of points, convex hulls, Voronoi diagrams, and many similar applications
  • Find out ways that SciPy can be used with other languages such as C/C++, Fortran, and MATLAB/Octave

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 26, 2015
Length: 188 pages
Edition : 2nd
Language : English
ISBN-13 : 9781783987719
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 26, 2015
Length: 188 pages
Edition : 2nd
Language : English
ISBN-13 : 9781783987719
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 126.97
Learning SciPy for Numerical and Scientific Computing Second Edition
$32.99
Mastering SciPy
$49.99
Mastering Matplotlib
$43.99
Total $ 126.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Introduction to SciPy Chevron down icon Chevron up icon
2. Working with the NumPy Array As a First Step to SciPy Chevron down icon Chevron up icon
3. SciPy for Linear Algebra Chevron down icon Chevron up icon
4. SciPy for Numerical Analysis Chevron down icon Chevron up icon
5. SciPy for Signal Processing Chevron down icon Chevron up icon
6. SciPy for Data Mining Chevron down icon Chevron up icon
7. SciPy for Computational Geometry Chevron down icon Chevron up icon
8. Interaction with Other Languages Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(10 Ratings)
5 star 40%
4 star 50%
3 star 10%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Omphaloskepsis Oct 22, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
its good if your a novice at using numpy, scipy, matplot;ib, etc . Not worth it if you use scypi all the time as I do , but still worth 5 stars if your just getitng started.
Amazon Verified review Amazon
Matteo May 06, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book provide a very good starting point to start using scipy for scientific computing. The book start with a basic python training and then continues with scipy proper. Exercises are sorta complex but given the topic it's no big deal. If you need to start using scipy for any or your project or you need to pick a language to help with your math studies this book is for you
Amazon Verified review Amazon
ABHIJIT Feb 28, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very GOOD book. Must buy.
Amazon Verified review Amazon
JLai Apr 08, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is really helpful!
Amazon Verified review Amazon
Mihai Racovitan Apr 13, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I bought an electronic version of this book directly from Packt Publishing at an incredible price. I use Python constantly, so I was curious what this book can provide. Three authors with experience in the architectures of high-performance number crunching with Python combined their experience into writing this book, so they offer quite a few valuable gems in writing code. The code is also available when you buy the electronic version. You do not need to be an advanced Python user since this book is written in an elegant combination of introducing the basics with presenting the challenges that may arise from using SciPy. For this reason is probably not recommended for high-level Python users which should be probably quite accustomed with the code written in this book.
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.