Convert dataframe to matrix in Julia

Convert dataframe to matrix in Julia

  • Julia
  • 2 mins read

To convert a dataframe to a matrix in Julia, you can use the matrix function. This function takes a dataframe and returns a matrix with the same data. Below are the examples:

Convert dataframe to matrix in Julia Examples

In this example, the dataframe df is converted to a 3x2 matrix. You can also specify the column(s) of the dataframe that you want to include in the matrix using the select function. For example:

julia> using DataFrames

julia> df = DataFrame(A = [1, 2, 3], B = [4, 5, 6])
3×2 DataFrame
│ Row │ A     │ B     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 5     │
│ 3   │ 3     │ 6     │

julia> convert(Matrix{Int64}, df)
3×2 Array{Int64,2}:
 1  4
 2  5
 3  6

Here are a few more advanced examples of converting a dataframe to a matrix in Julia:

julia> using DataFrames

julia> df = DataFrame(A = [1, 2, 3], B = [4, 5, 6], C = [7, 8, 9])
3×3 DataFrame
│ Row │ A     │ B     │ C     │
│     │ Int64 │ Int64 │ Int64 │
├─────┼───────┼───────┼───────┤
│ 1   │ 1     │ 4     │ 7     │
│ 2   │ 2     │ 5     │ 8     │
│ 3   │ 3     │ 6     │ 9     │

julia> matrix(select(df, Not([:B])))
3×2 Array{Int64,2}:
 1  7
 2  8
 3  9

julia> matrix(select(df, :A))
3×1 Array{Int64,2}:
 1
 2
 3

In the first example, the select function is used to exclude the B column from the dataframe, and the resulting dataframe is converted to a matrix. In the second example, the select function is used to only include the A column in the matrix.

In the third and fourth examples, the convert function is used to convert the selected dataframes to matrices of type Matrix{Int64}.

Related:

  1. Convert vector to matrix in Julia
  2. How to Create Matrix in Julia?
  3. Matrices in R