How can I save this data with CSV?

I am confused about the CSV way of writing files.
My problem is really simple:
I have two arrays and I want to save them in a .csv file, but I also want the following column names above my data: Voltage [V] and Current [A] which obviously are strings.

I tried an example with names tuples, but I don’t like that the names are propagated to the .csv as well:

diode_volt = []
diode_crt = []
append!(diode_volt, 0:0.1:10); 
append!(diode_crt, exp.(diode_volt));
# append header names

pushfirst!(diode_volt, β€œdiode voltage [V]”)
pushfirst!(diode_crt, β€œdiode current [A]”)
CSV.write(β€œdiode.csv”, (diode_volt = diode_volt, diode_crt = diode_crt))

What is the shortest way to solve this?

Nevermind, I read the docs more carefully and you can overwrite the header :sweat_smile::
CSV.write("diode.csv", (diode_volt = diode_volt, diode_crt = diode_crt); header = ["Voltage [V]", "Current [A]"])

1 Like

By default, CSV.write uses the namedtuple keys as column names, which is admittedly a bit awkward in your situation due to the spaces in the column names, but nevertheless, it would work to do:

tbl = NamedTuple{(Symbol("Voltage [V]"), Symbol("Current [A]"))}((
    0:0.1:10,
    exp.(0:0.1:10)
))
CSV.write("diode.csv", tbl)
3 Likes

You can use a dataframe which makes things somewhat simpler.

using DataFrames
df = DataFrames.DataFrame( Voltage = diode_volt,Current = diode_crt )

CSV.write("filename.csv", df)

Sadly this won’t allow you to add [V] or [A] as β€˜[’ and β€˜]’ are forbidden in variables names.

1 Like
julia> using DataFrames

julia> df = DataFrame("Voltage [V]" => rand(5), "Current [A]" => rand(5))
5Γ—2 DataFrame
β”‚ Row β”‚ Voltage [V] β”‚ Current [A] β”‚
β”‚     β”‚ Float64     β”‚ Float64     β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1   β”‚ 0.0793645   β”‚ 0.964186    β”‚
β”‚ 2   β”‚ 0.12372     β”‚ 0.921271    β”‚
β”‚ 3   β”‚ 0.223653    β”‚ 0.485401    β”‚
β”‚ 4   β”‚ 0.151043    β”‚ 0.242418    β”‚
β”‚ 5   β”‚ 0.885049    β”‚ 0.204711    β”‚

seems good to me?

3 Likes

that’s a nice way to it. I was using the keyword arguments but your solution with dic entries allows for arbitrary strings.

Thank you all for your solutions! In the end I used @quinnj’s method because I didn’t want to include DataFrames in the setup for such a simple table.