4

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

3
  • 1
    @AshishNitinPatil: genfromtxt is in numpy. Commented Mar 21, 2017 at 13:10
  • Presumably you mean that you tried importing the data with genfromtxt? Commented Mar 21, 2017 at 13:13
  • @BillBell yes, you're right. fixed Commented Mar 21, 2017 at 13:19

2 Answers 2

5

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!

Sign up to request clarification or add additional context in comments.

1 Comment

I managed by doing how you said and eliminating the space before the +. Thanks!
3

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.

2 Comments

I used replace from the data directly. data=fname.read() and than data=data.replace() But I guess it's exactly the same as you said
Yeah, the replace you can use whenever.. just before the actual parse to a complex number, since this must always be in the form "a+bj" in order to cast correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.