Reading complex numbers from csv file using python

I am having a problem reading a complex number from a csv file. The file format is as follows:

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

I tried to import data using numpy.genfromtxt:

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

But every time I have a difficult record, he returns me nan+0.j. I also tried removing the brackets before and after the number and replacing jwith 1j*, but that didn't work.

Any suggestions? Thanks

+4
source share
2 answers

I moved each "j" to a position immediately after the imaginary part of the complex number and squeezed out all the spaces to get an example 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 a code similar to yours, with a result similar to the following.

>>> 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]])

, , , .

!

+4

np.complex(str(a).replace('j', '') + 'j'

, 'j' .

+3

Source: https://habr.com/ru/post/1672821/


All Articles