Reputation: 107
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
Upvotes: 4
Views: 3066
Reputation: 1118
You can use
np.complex(str(a).replace('j', '') + 'j'
to first cast to a string, then shift the 'j' and cast back to a complex number.
Upvotes: 3
Reputation: 21643
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!
Upvotes: 5