Home > Back-end >  How do you create a dataframe out of arrays in Julia?
How do you create a dataframe out of arrays in Julia?

Time:10-01

How can I create a dataframe out of separate arrays?

For example, I want this, but 18 rows by two columns.

using DataFrames

df = DataFrame(
year = [[3:1:20;]],
amt = [fill(200, 18)]
)

CodePudding user response:

You don't need any arrays:

julia> using DataFrames

julia> df = DataFrame(year = 3:1:20, amt = 200)
18×2 DataFrame      
 Rowyear   amt   
     │ Int64  Int64 
─────┼──────────────
   13    200 
   24    200 
   35    200 
   46    200 
   57    200 
   68    200 
   79    200 
   810    200 
   911    200 
  1012    200 
  1113    200 
  1214    200 
  1315    200 
  1416    200 
  1517    200 
  1618    200 
  1719    200 
  1820    200 

If this seems a bit magical (passing a range object and a single value rather than arrays), you can get the same result if you pass in "real" arrays like DataFrame(year = collect(3:1:20), amt = fill(200, 18)). Note however that this is unnecessary and less efficient.

Also note that your enclosing square brackets are probably not what you're after: fill(200, 18) already creates an array:

julia> fill(200, 18)
18-element Vector{Int64}:
 200
 200

(Vector{Int} is an alias for Array{Int, 1}), while enclosing this in another set of brackets will create an array of length one, which holds your amt array as its only element:


julia> [fill(200, 18)]
1-element Vector{Vector{Int64}}:
 [200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
  • Related