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

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.