Constructing DataFrame from Dict with numeric keys in Julia

327 Views Asked by At

I would like to construct a DataFrames.jl data frame from a Julia Dict with integer numeric columns. I feel like this should be as simple as:

using DataFrames

mydict = Dict(1 => 1, 2 => 2)
mydf = DataFrame(mydict)

But this does not work because in this case, DataFrame expects a Dict with keys of type Symbol or string. What would be a concise way to construct a DataFrame from a Dict with non Symbol or string keys?

1

There are 1 best solutions below

2
On BEST ANSWER

Here are two examples how to do it:

julia> DataFrame(Symbol.(keys(mydict)) .=> values(mydict))
1×2 DataFrame
 Row │ 2      1
     │ Int64  Int64
─────┼──────────────
   1 │     2      1

julia> DataFrame(Symbol(k) => v for (k, v) in pairs(mydict))
2×2 DataFrame
 Row │ first   second
     │ Symbol  Int64
─────┼────────────────
   1 │ 2            2
   2 │ 1            1

The reason why we only accept strings or Symbol values as column names is that, in general, even if two keys would be considered different in source dictionary they might have a string representation, causing ambiguity.

For this reason and user safety both DataFrames.jl and Tables.jl assume that column names cannot be arbitrary values.