Hello, In [2]: numpy.real(arange(3)) Out[2]: array([0, 1, 2]) In [3]: numpy.complex(arange(3)) TypeError: only length-1 arrays can be converted to Python scalars Are there any reasons why numpy.complex doesn't work on arrays? Should it be bug reported? Thanks for your help C. Molinaro
On Wed, 2012-07-18 at 15:14 +0200, Molinaro Céline wrote:
In [2]: numpy.real(arange(3)) Out[2]: array([0, 1, 2]) In [3]: numpy.complex(arange(3)) TypeError: only length-1 arrays can be converted to Python scalars
Are there any reasons why numpy.complex doesn't work on arrays? Should it be bug reported?
numpy.complex is just a reference to the built in complex, so only works on scalars: In [5]: numpy.complex is complex Out[5]: True Try numpy.complex128 (or another numpy.complexN, with N being the bit length). Henry
On 18 July 2012 15:14, Molinaro Céline <celine.molinaro@telecom-bretagne.eu> wrote:
Hello,
In [2]: numpy.real(arange(3)) Out[2]: array([0, 1, 2]) In [3]: numpy.complex(arange(3)) TypeError: only length-1 arrays can be converted to Python scalars
I think you're looking for the dtype keyword to the ndarray constructor: import numpy as np np.arange(3, dtype=np.complex) Out[2]: array([ 0.+0.j, 1.+0.j, 2.+0.j]) or if you have an existing array to cast: np.asarray(np.arange(3), dtype=np.complex) Out[3]: array([ 0.+0.j, 1.+0.j, 2.+0.j]) You can get the real and imaginary components of your complex array like so: a = np.arange(3, dtype=np.complex) a Out[9]: array([ 0.+0.j, 1.+0.j, 2.+0.j]) a.real Out[10]: array([ 0., 1., 2.]) a.imag Out[11]: array([ 0., 0., 0.]) Cheers, Scott
participants (3)
-
Henry Gomersall
-
Molinaro Céline
-
Scott Sinclair