Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read complex numbers from a csv file using python

Tags:

python

csv

numpy

I am having problem reading complex number from a csv file. The format of the file is the following:

( -353.10438 +j1.72317617 ),( -23.16000 +j0.72512251 )

I tried importing the data using numpy.genfromtxt:

data=genfromtxt(fname, dtype=complex, skip_header=10, skip_footer=212, delimiter=',')

But every time I have a complex entry it returns me nan+0.j. I also tried removing the brackets before and after the number, and replacing the j with 1j* but it didn't work.

Any suggestions? Thanks

like image 247
gian9 Avatar asked Feb 04 '23 20:02

gian9


1 Answers

I moved each 'j' to the position immediately behind the imaginary part of the complex number and squeezed out all the blanks to get a sample file like this.

(-353.10438+1.72317617j),(-23.16000+0.72512251j)
(-353.10438+1.72317617j),(-23.16000+0.72512251j)
(-353.10438+1.72317617j),(-23.16000+0.72512251j)
(-353.10438+1.72317617j),(-23.16000+0.72512251j)

Then I ran code similar to yours with a result similar to what follows.

>>> np.genfromtxt('fname.txt', dtype=complex, delimiter=',')
array([[-353.10438+1.72317617j,  -23.16000+0.72512251j],
       [-353.10438+1.72317617j,  -23.16000+0.72512251j],
       [-353.10438+1.72317617j,  -23.16000+0.72512251j],
       [-353.10438+1.72317617j,  -23.16000+0.72512251j]])

I don't know exactly what you might have to do to get similar results, if indeed this approach will work for you at all.

Best of luck!

like image 86
Bill Bell Avatar answered Feb 07 '23 19:02

Bill Bell