Davi Barreira
Davi Barreira

Reputation: 1681

Julia - How to conver DataFrame to Array?

I have a DataFrame containing only numerical values. Now, what I'd like to do is extract all the values of this DataFrame as an Array. How can I do this? I know that for a single column, if I do df[!,:x1], then the output is an array. But how to do this for all the columns?

Upvotes: 6

Views: 6467

Answers (3)

You can also use the Tables API for this, in particular the Tables.matrix function:

julia> df = DataFrame(x=rand(3), y=rand(3))
3×2 DataFrame
 Row │ x          y        
     │ Float64    Float64  
─────┼─────────────────────
   1 │ 0.33002    0.180934
   2 │ 0.834302   0.470976
   3 │ 0.0916842  0.45172

julia> Tables.matrix(df)
3×2 Array{Float64,2}:
 0.33002    0.180934
 0.834302   0.470976
 0.0916842  0.45172

Upvotes: 5

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42244

The shortest form seems to be:

julia> Matrix(df)
3×2 Array{Float64,2}:
 0.723835  0.307092
 0.02993   0.0147598
 0.141979  0.0271646

In some scenarios you might want need to specify the type such as Matrix{Union{Missing, Float64}}(df)

Upvotes: 9

Andy_101
Andy_101

Reputation: 1306

convert(Matrix, df[:,:])

Try this

Upvotes: 3

Related Questions