Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

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.flatten...