qgp07
qgp07

Reputation: 305

How do I load a csv file with complex numbers in julia?

I am trying to access some complex numbers I wrote to a csv file in julia but I'm having trouble getting it to recognize them. To understand what is happening, consider the following

a = [1+2.3im, 2.3+0im]
writecsv("test.csv",a)
b = readcsv("test.csv")

Now, if I interrogate the types

julia> typeof(b)
Array{Any,2}

julia> typeof(a)
Array{Complex{Float64},1}

And I cannot use the elements of b as complex numbers, just as a string.(b[1] is "1.0 + 2.3im", for instance).

Upvotes: 7

Views: 964

Answers (2)

Lianying Ji
Lianying Ji

Reputation: 21

if you are using CSV and DataFrame, you can use

CSV.read("test.CSV", DataFrame, types=Complex{Float64})

Upvotes: 2

rickhg12hs
rickhg12hs

Reputation: 11922

Here's one way:

julia> b = map(x->eval(parse(x)),readcsv("test.csv"))
2x1 Array{Complex{Float64},2}:
 1.0+2.3im
 2.3+0.0im

Upvotes: 8

Related Questions