using DelimitedFiles with title of the header

Viewed 201

When importing a .csv file, is there any way to read the data from the title of the header? Consider the .csv file in the following:

I mean, instead of start_node = round.(Int64, data[:,1]) is there another way to say "start_node" is the one in the .csv file that its header is "start node i"

# Importing packages
using  DelimitedFiles



# Data Preparation
network_data_file = "network.csv"
network_data = readdlm(network_data_file, ',', header=true)
data = network_data[1]
header = network_data[2]

start_node = round.(Int64, data[:,1])
end_node = round.(Int64, data[:,2])

enter image description here

1 Answers

The most natural way is to use CSV along with the DataFrames package.

Consider file:

 open("f.txt", "w") do f
       println(f,"""start;end;c
              1;2;3
              4;5;6
              """)
       end

You can do:

julia> df = CSV.File("f.txt") |> DataFrame
2×3 DataFrame
 Row │ start  end    c
     │ Int64  Int64  Int64
─────┼─────────────────────
   1 │     1      2      3
   2 │     4      5      6

and now:

julia> df.start
2-element Vector{Int64}:
 1
 4

If you want to stick with DelimitedFiles you could do:

julia> res = readdlm("f.txt",';'; header=true);


julia> DataFrame(res[1], vec(res[2]))
2×3 DataFrame
 Row │ start    end      c
     │ Float64  Float64  Float64
─────┼───────────────────────────
   1 │     1.0      2.0      3.0
   2 │     4.0      5.0      6.0

Going totally without any package:

julia> res[1][:,findfirst(==("start"), vec(res[2]))]
2-element Vector{Float64}:
 1.0
 4.0

Finally, it is worth noting that if you want readdlm to yield Ints instead of Float64s you could read data as readdlm("f.txt",';',Int,'\n'; header=true)

Related