将字典导出到 julia 中的 CSV 文件?

时间:2021-04-06 02:12:16

标签: csv dictionary julia export-to-csv

我想知道,如何将嵌套的 dictionary 直接导出到 Julia 中的 CSV file

例如:我有以下字典 ->

d = Dict(:a => Dict(:val1 => rand(4), :val2 => rand(450)),
    :b => Dict(:val1 => rand(4), :val2 => rand(1500)));

问题是以下内容的大小不规则,因此难以转换为数据帧。 有没有直接的替代方法可以导出这种不规则的字典。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将嵌套键更改为 CSV 文件的列,但这会浪费磁盘空间和内存,因为您随后在每一行中重复所有键,每个底层数据一行:

using DataFrames

const d = Dict(:a => Dict(:val1 => rand(4), :val2 => rand(450)),
    :b => Dict(:val1 => rand(4), :val2 => rand(1500)));
   
const alen, blen = 4 + 450, 4 + 1500
    
df = DataFrame(
    letters = vcat(fill(:a, alen), fill(:b, blen)),
    vals = vcat(fill(:val1, 4), fill(:val2, 450),
         fill(:val1, 4), fill(:val2, 1500)),
    rands = vcat(values(d[:a][:val1]), values(d[:a][:val2]),
         values(d[:b][:val1]), values(d[:b][:val2]))
)

@show filter(r -> r.letters == :a && r.vals == :val1, df)

CSV.write(pathname, df)

在您的示例中,这会为每个随机值使用几个额外的字节,因为每行都有以 a,val1, 开头的冗余条目。因此,出于空间原因,JLD2 会更好,除非您将 CSV 提供给需要该格式的程序。

相关问题