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
Numpy Beginner's Guide (Update)
Numpy Beginner's Guide (Update)

Numpy Beginner's Guide (Update): Build efficient, high-speed programs using the high-performance NumPy mathematical library

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.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

Numpy Beginner's Guide (Update)

Chapter 2. Beginning with NumPy Fundamentals

After installing NumPy and getting some code to work, it's time to cover NumPy basics.

The topics we shall cover in this chapter are as follows:

  • Data types
  • Array types
  • Type conversions
  • Array creation
  • Indexing
  • Slicing
  • Shape manipulation

Before we start, let me make a few remarks about the code examples in this chapter. The code snippets in this chapter show input and output from several IPython sessions. Recall that IPython was introduced in Chapter 1, NumPy Quick Start, as the interactive Python shell of choice for scientific computing. The advantages of IPython are the --pylab switch that imports many scientific computing Python packages, including NumPy, and the fact that it is not necessary to explicitly call the print() function to display variable values. Other features include easy parallel computation and the notebook interface in the form of a persistent worksheet in a web browser.

However, the source code delivered alongside the...

NumPy array object

NumPy has a multidimensional array object called ndarray. It consists of two parts:

  • The actual data
  • Some metadata describing the data

The majority of array operations leave the raw data untouched. The only aspect that changes is the metadata.

In the previous chapter, we have already learned how to create an array using the arange() function. Actually, we created a one-dimensional array that contained a set of numbers. The ndarray object can have more than one dimension.

The NumPy array is in general homogeneous (there is a special array type that is heterogeneous as described in the Time for action – creating a record data type section)—the items in the array have to be of the same type. The advantage is that, if we know that the items in the array are of the same type, it is easy to determine the storage size required for the array.

NumPy arrays are indexed starting from 0, just like in Python. Data types are represented by special objects. We will discuss these...

Time for action – creating a multidimensional array

Now that we know how to create a vector, we are ready to create a multidimensional NumPy array. After we create the array, we will again want to display its shape:

  1. Create a two-by-two array:
    In: m = array([arange(2), arange(2)])
    In: m
    Out:
    array([[0, 1],
          [0, 1]])
    
  2. Show the array shape:
    In: m.shape
    Out: (2, 2)
    

What just happened?

We created a two-by-two array with the arange() and array() functions we have come to trust and love. Without any warning, the array() function appeared on the stage.

The array() function creates an array from an object that you give to it. The object needs to be array-like, for instance, a Python list. In the preceding example, we passed in a list of arrays. The object is the only required argument of the array() function. NumPy functions tend to have a lot of optional arguments with predefined defaults. View the documentation for this function from the IPython shell with the help() function given here...

Time for action – creating a record data type

The record data type is a heterogeneous data type—think of it as representing a row in a spreadsheet or a database. To give an example of a record data type, we will create a record for a shop inventory. The record contains the name of the item, a 40-character string, the number of items in the store represented by a 32-bit integer, and, finally, a price represented by a 32-bit float. These consecutive steps show how to create a record data type:

  1. Create the record:
    In: t = dtype([('name', str_, 40), ('numitems', int32), ('price', float32)])
    In: t
    Out: dtype([('name', '|S40'), ('numitems', '<i4'), ('price', '<f4')])
    
  2. View the type (we can view the type of a field as well):
    In: t['name']
    Out: dtype('|S40')
    

If you don't give the array() function a data type, it will assume that it is dealing with floating point numbers...

One-dimensional slicing and indexing

Slicing of one-dimensional NumPy arrays works just like slicing of Python lists. Select a piece of an array from index 3 to 7 that extracts the elements 3 through 6:

In: a = arange(9)
In: a[3:7]
Out: array([3, 4, 5, 6])

Select elements from index 0 to 7 with step 2 as follows:

In: a[:7:2]
Out: array([0, 2, 4, 6])

Similarly, as in Python, use negative indices and reverse the array with this code snippet:

In: a[::-1]
Out: array([8, 7, 6, 5, 4, 3, 2, 1, 0])

Time for action – slicing and indexing multidimensional arrays

The ndarray class supports slicing over multiple dimensions. For convenience, we refer to many dimensions at once, with an ellipsis.

  1. To illustrate, create an array with the arange() function and reshape it:
    In: b = arange(24).reshape(2,3,4)
    In: b.shape
    Out: (2, 3, 4)
    In: b
    Out:
    array([[[ 0,  1,  2,  3],
            [ 4,  5,  6,  7],
            [ 8,  9, 10, 11]],
           [[12, 13, 14, 15],
            [16, 17, 18, 19],
            [20, 21, 22, 23]]])
    

    The array b has 24 elements with values 0 to 23 and we reshaped it to be a two-by-three-by-four, three-dimensional array. We can visualize this as a two-story building with 12 rooms on each floor, 3 rows and 4 columns (alternatively we can think of it as a spreadsheet with sheets, rows, and columns). As you have probably guessed, the reshape() function changes the shape of an array. We give it a tuple of integers, corresponding to the new shape. If the dimensions are not compatible with the...

Time for action – manipulating array shapes

We already learned about the reshape() function. Another recurring task is flattening of arrays. When we flatten multidimensional NumPy arrays, the result is a one-dimensional array with the same data.

  1. Ravel: Accomplish this with the ravel() function:
    In: b
    Out:
    array([[[ 0,  1,  2,  3],
            [ 4,  5,  6,  7],
            [ 8,  9, 10, 11]],
           [[12, 13, 14, 15],
            [16, 17, 18, 19],
            [20, 21, 22, 23]]])
    In: b.ravel()
    Out:
    array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
           17, 18, 19, 20, 21, 22, 23])
    
  2. Flatten: The appropriately named function, flatten() does the same as ravel(), but flatten() always allocates new memory whereas ravel() might return a view of the array. A view is a way to share an array, but you need to be careful with views because modifying the view affects the underlying array, and therefore this impacts other views. An array copy is safer; however, it uses more memory:
    In: b...

Time for action – stacking arrays

First, set up some arrays:

In: a = arange(9).reshape(3,3)
In: a
Out:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In: b = 2 * a
In: b
Out:
array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
  1. Horizontal stacking: Starting with horizontal stacking, form a tuple of the ndarray objects and give it to the hstack() function as follows:
    In: hstack((a, b))
    Out:
    array([[ 0,  1,  2,  0,  2,  4],
           [ 3,  4,  5,  6,  8, 10],
           [ 6,  7,  8, 12, 14, 16]])
    

    Achieve the same with the concatenate() function as follows (the axis argument here is equivalent to axes in a Cartesian coordinate system and corresponds to the array dimensions):

    In: concatenate((a, b), axis=1)
    Out:
    array([[ 0,  1,  2,  0,  2,  4],
           [ 3,  4,  5,  6,  8, 10],
           [ 6,  7,  8, 12, 14, 16]])
    

    This image shows horizontal stacking with the concatenate() function:

    Time for action – stacking arrays
  2. Vertical stacking: With vertical stacking, again, a tuple is formed. This time, it is given to the...

Time for action – splitting arrays

The following steps demonstrate arrays splitting:

  1. Horizontal splitting: The ensuing code splits an array along its horizontal axis into three pieces of the same size and shape:
    In: a
    Out:
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])
    In: hsplit(a, 3)
    Out:
    [array([[0],
           [3],
           [6]]),
     array([[1],
           [4],
           [7]]),
     array([[2],
           [5],
           [8]])]
    

    Compare it with a call of the split() function, with extra parameter axis=1:

    In: split(a, 3, axis=1)
    Out:
    [array([[0],
           [3],
           [6]]),
     array([[1],
           [4],
           [7]]),
     array([[2],
           [5],
           [8]])]
    
  2. Vertical splitting: vsplit() splits along the vertical axis:
    In: vsplit(a, 3)
    Out: [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]
    

    The split() function, with axis=0, also splits along the vertical axis:

    In: split(a, 3, axis=0)
    Out: [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]
    
  3. Depth-wise splitting: The dsplit() function, unsurprisingly...

Time for action – converting arrays

Convert a NumPy array to a Python list with the tolist() function:

  1. Convert to a list:
    In: b
    Out: array([ 1.+1.j,  3.+2.j])
    In: b.tolist()
    Out: [(1+1j), (3+2j)]
    
  2. The astype() function converts the array to an array of the specified type:
    In: b
    Out: array([ 1.+1.j,  3.+2.j])
    In: b.astype(int)
    /usr/local/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part
      #!/usr/bin/python
    Out: array([1, 3])
    

    Note

    We are losing the imaginary part when casting from the NumPy complex type (not the plain vanilla Python one) to int. The astype() function also accepts the name of a type as a string.

    In: b.astype('complex')
    Out: array([ 1.+1.j,  3.+2.j])
    

It won't show any warning this time because we used the proper data type.

What just happened?

We converted NumPy arrays to a list and to arrays of different data types. The code for this example is in the arrayconversion.py file in this book's code bundle.

Summary

In this chapter, you learned a lot about NumPy fundamentals: data types and arrays. Arrays have several attributes describing them. You learned that one of these attributes is the data type, which, in NumPy, is represented by a fully-fledged object.

NumPy arrays can be sliced and indexed in an efficient manner, just like Python lists. NumPy arrays have the added ability of working with multiple dimensions.

The shape of an array can be manipulated in many ways—stacking, resizing, reshaping, and splitting. A great number of convenience functions for shape manipulation were demonstrated in this chapter.

Having learned about the basics, it's time to move on to the study of commonly used functions in Chapter 3, Getting Familiar with Commonly Used Functions, which includes basic statistical and mathematical functions.

Left arrow icon Right arrow icon

Description

This book is for the scientists, engineers, programmers, or analysts looking for a high-quality, open source mathematical library. Knowledge of Python is assumed. Also, some affinity, or at least interest, in mathematics and statistics is required. However, I have provided brief explanations and pointers to learning resources.

Who is this book for?

This book is for the scientists, engineers, programmers, or analysts looking for a high-quality, open source mathematical library. Knowledge of Python is assumed. Also, some affinity, or at least interest, in mathematics and statistics is required. However, I have provided brief explanations and pointers to learning resources.

What you will learn

  • Install NumPy, matplotlib, SciPy, and IPython on various operating systems
  • Use NumPy array objects to perform array operations
  • Familiarize yourself with commonly used NumPy functions
  • Use NumPy matrices for matrix algebra
  • Work with the NumPy modules to perform various algebraic operations
  • Test NumPy code with the numpy.testing module
  • Plot simple plots, subplots, histograms, and more with matplotlib

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 24, 2015
Length: 348 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288838
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 : Jun 24, 2015
Length: 348 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288838
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 94.97
Learning SciPy for Numerical and Scientific Computing Second Edition
€24.99
Numpy Beginner's Guide (Update)
€36.99
Mastering Matplotlib
€32.99
Total 94.97 Stars icon
Banner background image

Table of Contents

15 Chapters
1. NumPy Quick Start Chevron down icon Chevron up icon
2. Beginning with NumPy Fundamentals Chevron down icon Chevron up icon
3. Getting Familiar with Commonly Used Functions Chevron down icon Chevron up icon
4. Convenience Functions for Your Convenience Chevron down icon Chevron up icon
5. Working with Matrices and ufuncs Chevron down icon Chevron up icon
6. Moving Further with NumPy Modules Chevron down icon Chevron up icon
7. Peeking into Special Routines Chevron down icon Chevron up icon
8. Assuring Quality with Testing Chevron down icon Chevron up icon
9. Plotting with matplotlib Chevron down icon Chevron up icon
10. When NumPy Is Not Enough – SciPy and Beyond Chevron down icon Chevron up icon
11. Playing with Pygame Chevron down icon Chevron up icon
A. Pop Quiz Answers Chevron down icon Chevron up icon
B. Additional Online Resources Chevron down icon Chevron up icon
C. NumPy Functions' References Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 100%
1 star 0%
Alexander Sagel Jan 10, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
it's a helpful guide. however, the code examples are inconsistent in style and overflowing with mistakes. requires a thorough revision
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.