Nico Schlömer Nico Schlömer - 3 months ago 28
Python Question

Convert complex NumPy array into (n, 2)-array of real and imaginary parts

I have a complex-valued NumPy array that I'd like to convert into a contiguous NumPy array with real and imaginary parts separate.

This



import numpy

u = numpy.array([
1.0 + 2.0j,
2.0 + 4.0j,
3.0 + 6.0j,
4.0 + 8.0j
])

u2 = numpy.ascontiguousarray(numpy.vstack((u.real, u.imag)).T)


does the trick, but transposing, vstacking, and converting to a contiguous array is probably a step or two too much.

Is there a native NumPy function that does this for me?

Answer

You can use dstack:

np.dstack((u.real, u.imag))[0]
#Out[210]:
#array([[ 1.,  2.],
#       [ 2.,  4.],
#       [ 3.,  6.],
#       [ 4.,  8.]])