【问题标题】:how to create dictionary from julia dataframe?如何从 julia 数据框创建字典?
【发布时间】:2020-09-05 08:45:19
【问题描述】:

我有一个像下面这样的 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 julia-dataframe


    【解决方案1】:

    要从数据框中创建字典,您可以编写:

    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"
    

    【讨论】:

    • 不客气 :)。我希望它有所帮助。关键是 pandas 中的许多自定义功能只是 Julia Base 中的标准功能。
    • 我完全同意你的观点,先生
    猜你喜欢
    • 2019-05-27
    • 2020-05-10
    • 1970-01-01
    • 2021-12-30
    • 2021-08-10
    • 2016-05-22
    • 2022-06-13
    • 2016-01-14
    相关资源
    最近更新 更多