How to Output a 2D Array to a CSV File in Julia
Code
using CSV, DataFrames
A = rand(1:10, 10)
B = zeros(10)
AB = DataFrame(hcat(A,B), ["A", "B"])
CSV.write("AB.csv", AB)
The write
function of the CSV
package allows you to easily output a two-dimensional array. A
, B
are one-dimensional arrays, which are combined using the hcat
function to transform into a dataframe.
Execution Result
julia> using CSV, DataFrames
julia> A = rand(1:10, 10)
10-element Array{Int64,1}:
8
5
4
3
6
4
10
6
2
9
julia> B = zeros(10)
10-element Array{Float64,1}:
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
julia> AB = DataFrame(hcat(A,B), ["A", "B"])
10×2 DataFrame
Row │ A B
│ Float64 Float64
─────┼──────────────────
1 │ 8.0 0.0
2 │ 5.0 0.0
3 │ 4.0 0.0
⋮ │ ⋮ ⋮
9 │ 2.0 0.0
10 │ 9.0 0.0
5 rows omitted
julia> CSV.write("AB.csv", AB)
"AB.csv"
Here is the actual csv file that was output.
See Also
Environment
- OS: Windows
- julia: v1.6.3