Convert Array to DataFrame in Julia

Convert Array to DataFrame in Julia

  • Julia
  • 2 mins read

To convert an array to a dataframe in Julia, you can use the DataFrame function from the DataFrames package. Below are the examples:

Convert Array to DataFrame in Julia

You can specify the column names for the dataframe. For example, the following code will create a dataframe with two columns, A and B, containing the values from the array:

using DataFrames

# Define the array
arr = [1, 2, 3, 4, 5]

# Convert the array to a dataframe with two columns
df = DataFrame(A = arr, B = arr)

# Print the dataframe
println(df)

The output will be a dataframe with two columns, each containing the values from the array:

5×2 DataFrame
 Row │ A      B     
     │ Int64  Int64 
─────┼──────────────
   1 │     1      1
   2 │     2      2
   3 │     3      3
   4 │     4      4
   5 │     5      5

Here is an example of how you can convert the 2D array to a dataframe using the DataFrame function and specifying the values for each column:

using DataFrames

# Define the 2D array
arr = [    [1],
    [4],
    [7]
]

# Convert the array to a dataframe with three columns
df = DataFrame(A = arr[:,1], B = arr[:,1], C = arr[:,1])

# Print the dataframe
println(df)

This code will create a dataframe with three columns, A, B, and C, each containing the values from the first column of the array. The output will look like this:

3×3 DataFrame
 Row │ A       B       C      
     │ Array…  Array…  Array… 
─────┼────────────────────────
   1 │ [1]     [1]     [1]
   2 │ [4]     [4]     [4]
   3 │ [7]     [7]     [7]

Alternatively, you can create separate arrays or vectors for each column, and then use the DataFrame function to convert the arrays to a dataframe. Here is an example of how you can do this:

using DataFrames

# Define the 2D array
arr = [    [1],
    [4],
    [7]
]

# Create separate arrays or vectors for each column
A = arr[:,1]
B = arr[:,1]
C = arr[:,1]

# Convert the arrays to a dataframe with three columns
df = DataFrame(A = A, B = B, C = C)

# Print the dataframe
println(df)

This code will create a dataframe with three columns, A, B, and C, each containing the values from the corresponding columns in the array. The output will look like this:

3×3 DataFrame
 Row │ A       B       C      
     │ Array…  Array…  Array… 
─────┼────────────────────────
   1 │ [1]     [1]     [1]
   2 │ [4]     [4]     [4]
   3 │ [7]     [7]     [7]

Related:

  1. How to Create DataFrame in Julia?
  2. Convert dataframe to matrix in Julia