Export an array to a CSV file in Julia
Asked Answered
L

1

23

Given a (2d) array A how to export it into a CSV file with Julia?

Back in the older versions, I would write

writecsv( "FileName.csv",  A);

which would dump the array A into the given file. This, however, does not work in version >= 1.0. After some googling, I also tried to use the CSV module doing

f = open("test.csv", "a+");
CSV.write(f, A; delim = ',')

but this throws an error

ERROR: ArgumentError: no default `Tables.rows` implementation for type: Array{Int64,2}

(my array A was of type Int64).

Does anyone have a working solution for this most trivial question?

Lobar answered 19/10, 2018 at 21:38 Comment(0)
P
37

You need to load DelimitedFiles module and now only writedlm function is supported.

So in order to write an array as CSV file use:

julia> using DelimitedFiles

julia> writedlm( "FileName.csv",  A, ',')

To get the same result with CSV.jl package use:

julia> using CSV, Tables

julia> CSV.write("FileName.csv",  Tables.table(A), writeheader=false)

as Matrix does not support Tables.jl interface so you need to wrap it with Tables.table.

Peursem answered 19/10, 2018 at 22:31 Comment(3)
Not sure if this is always needed, but note that you may have to add the :auto argument, as in DataFrame(A, :auto). Bogumił, is this the newer practice? Thanks. Quote: "DataFrame constructor from a Matrix requires passing :auto as a second argument to automatically generate column names: DataFrame(matrix, :auto)"Along
yes, now :auto is required. I updated the answer with the currently recommended practice - Tables.table which does not copy.Pustulate
When I try this fix I get the error message MethodError: no method matching table(::Array{Int64, 3}). Is this because I can't write a 3d array to a .csv file? Is here any way in julia to write a 3d array to a .csv file?Photography

© 2022 - 2024 — McMap. All rights reserved.