Converting Between DataFrames and 2D Arrays in Julia
Code
Matrix(df)
or Array(df)
functions can be used to convert a DataFrame into an array of the same size. To create a DataFrame from an array, use DataFrame(array, :auto)
. In the past, the convert
function was used, but it’s not applicable anymore, so be careful.
using DataFrames
julia> A = rand(5,3)
5×3 Matrix{Float64}:
0.678876 0.10431 0.827079
0.621647 0.372007 0.29346
0.756844 0.171237 0.0732631
0.922519 0.0535938 0.121689
0.164058 0.0684278 0.68446
julia> df = DataFrame(A, :auto)
5×3 DataFrame
Row │ x1 x2 x3
│ Float64 Float64 Float64
─────┼────────────────────────────────
1 │ 0.678876 0.10431 0.827079
2 │ 0.621647 0.372007 0.29346
3 │ 0.756844 0.171237 0.0732631
4 │ 0.922519 0.0535938 0.121689
5 │ 0.164058 0.0684278 0.68446
julia> Matrix(df)
5×3 Matrix{Float64}:
0.678876 0.10431 0.827079
0.621647 0.372007 0.29346
0.756844 0.171237 0.0732631
0.922519 0.0535938 0.121689
0.164058 0.0684278 0.68446
julia> Array(df)
5×3 Matrix{Float64}:
0.678876 0.10431 0.827079
0.621647 0.372007 0.29346
0.756844 0.171237 0.0732631
0.922519 0.0535938 0.121689
0.164058 0.0684278 0.68446
julia> Array(df) == Matrix(df)
true