Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 355
Duncan Tait Avatar asked Apr 08 '10 09:04

Duncan Tait


People also ask

How do you create a 2 dimensional NumPy array?

In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.

Can NumPy array have mixed types?

Introduction to Data Types Having a data type (dtype) is one of the key features that distinguishes NumPy arrays from lists. In lists, the types of elements can be mixed. One index of a list can contain an integer, another can contain a string.


1 Answers

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.

like image 54
Eric O Lebigot Avatar answered Sep 22 '22 00:09

Eric O Lebigot