Converting arrays

To convert an array to a Python list we use tolist() function.

d = np.array([1.j + 1, 2.j + 3])
print(d)
d.tolist()

#out
array([ 1.+1.j,  3.+2.j])
b.tolist()
b

#out
[ 1.+1.j  3.+2.j]
[(1+1j), (3+2j)]

You can convert an array to a specific data type using astype() function.

d.astype(int)
/home/ddn_ro/env/data_analysis/lib/python3.5/site-packages/ipykernel_launcher.py:1: ComplexWarning: Casting complex values to real discards the imaginary part
    #Entry point for launching an IPython kernel.

#out
array([1, 3])

When transforming from complex to int the imaginary part is left off; that’s what the warning says. We won’t get the warning if we use complex instead of int.

d.astype(complex)

#out
array([ 1.+1.j,  3.+2.j])

Leave a Reply