stackoverflow,
I have a matrix containing complex numbers (ex. -2.2982235934153075E-11+2.1179547211742553E-9i) that I need to import to a numpy array. I've been using genfromtext(file) to parse all my other, real values, but I'm getting a nan for all complex values. Any ideas?
self.raw = (genfromtxt(self.loc, delimiter=',', skip_header=9, dtype=float))
[m,n] = shape(self.raw)
data = zeros((m, n-3))
data[:, :] = self.raw[:, 3::]
returns:
data = array([nan, nan, nan, ...])
You can do:
import numpy as np
a = np.genfromtxt(filename, converters={0: lambda x: x.replace('i','j')},
dtype=str)
a = np.complex_(a)
Note that the converters parameter was required because your text file is using i to denote the imaginary part.
It may be easier to convert your text file externally to replace all the i by j, avoiding a complicated converters argument in case you have many columns.
If your textfile with imaginary numbers had the format:
(-2.298223593415307508e-11+2.117954721174255306e-09j)
(-2.298223593415307508e-11+2.117954721174255306e-09j)
(-2.298223593415307508e-11+2.117954721174255306e-09j)
(-2.298223593415307508e-11+2.117954721174255306e-09j)
(-2.298223593415307508e-11+2.117954721174255306e-09j)
(-2.298223593415307508e-11+2.117954721174255306e-09j)
(-2.298223593415307508e-11+2.117954721174255306e-09j)
Where you could read using only:
a = np.loadtxt(filename).view(complex)
for example...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With