Search code examples
pythonarraysnumpycomplex-numbers

Numpy: Creating a complex array from 2 real ones?


I want to combine 2 parts of the same array to make a complex array:

Data[:,:,:,0] , Data[:,:,:,1]

These don't work:

x = np.complex(Data[:,:,:,0], Data[:,:,:,1])
x = complex(Data[:,:,:,0], Data[:,:,:,1])

Am I missing something? Does numpy not like performing array functions on complex numbers? Here's the error:

TypeError: only length-1 arrays can be converted to Python scalars

Solution

  • This seems to do what you want:

    numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data)
    

    Here is another solution:

    # The ellipsis is equivalent here to ":,:,:"...
    numpy.vectorize(complex)(Data[...,0], Data[...,1])
    

    And yet another simpler solution:

    Data[...,0] + 1j * Data[...,1]
    

    PS: If you want to save memory (no intermediate array):

    result = 1j*Data[...,1]; result += Data[...,0]
    

    devS' solution below is also fast.