Home Β» Julia Β» Convert dataframe to matrix in Julia

Convert dataframe to matrix in Julia

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