Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy read .csv with complex number

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, ...])
like image 578
1ifbyLAN2ifbyC Avatar asked May 11 '26 22:05

1ifbyLAN2ifbyC


1 Answers

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...

like image 59
Saullo G. P. Castro Avatar answered May 13 '26 10:05

Saullo G. P. Castro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!