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
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783987702
Category :
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 95.97
Learning SciPy for Numerical and Scientific Computing Second Edition
€24.99
Mastering SciPy
€37.99
Mastering Matplotlib
€32.99
Total 95.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.