如何从 julia 数据框创建字典?

how to create dictionary from julia dataframe?

我有一个如下所示的 df,我想从 df 中获取字典。

df = DataFrame(id=[1, 2, 3, 4], value=["Rajesh", "John", "Jacob", "sundar"], other=[0.43, 0.42,0.54, 0.63])

│ Row │ id    │ value  │ other   │
│     │ Int64 │ String │ Float64 │
├─────┼───────┼────────┼─────────┤
│ 1   │ 1     │ Rajesh │ 0.43    │
│ 2   │ 2     │ John   │ 0.42    │
│ 3   │ 3     │ Jacob  │ 0.54    │
│ 4   │ 4     │ sundar │ 0.63    │

预期输出:

{1: 'Rajesh', 2: 'John', 3: 'Jacob', 4: 'sundar'}

我知道如何在 pandas、

中执行此操作
df.set_index("id")["value"].to_dict()

pandas 在 julia 中的等效代码是什么?

要从数据框创建字典,您可以这样写:

julia> Dict(pairs(eachcol(df)))
Dict{Symbol,AbstractArray{T,1} where T} with 3 entries:
  :value => ["Rajesh", "John", "Jacob", "sundar"]
  :id    => [1, 2, 3, 4]
  :other => [0.43, 0.42, 0.54, 0.63]

但是,您要求的是从向量(恰好存储在数据框中)创建字典,您可以通过以下方式进行操作(模式非常相似,但只是应用于向量):

julia> Dict(pairs(df.value))
Dict{Int64,String} with 4 entries:
  4 => "sundar"
  2 => "John"
  3 => "Jacob"
  1 => "Rajesh"

如果你想要从 :id:value 的映射,请写入(假设 :id 是唯一的;同样 - 它只是两个向量,事实上它们存储在数据框在这里并不重要):

julia> Dict(Pair.(df.id, df.value))
Dict{Int64,String} with 4 entries:
  4 => "sundar"
  2 => "John"
  3 => "Jacob"
  1 => "Rajesh"