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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Spain

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 : 9781785281969
Category :
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Spain

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Jun 24, 2015
Length: 348 pages
Edition : 1st
Language : English
ISBN-13 : 9781785281969
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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela