Time for action – converting arrays
Convert a NumPy array to a Python list with the tolist()
function:
- Convert to a list:
In: b Out: array([ 1.+1.j, 3.+2.j]) In: b.tolist() Out: [(1+1j), (3+2j)]
- 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
. Theastype()
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.