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