Moh*_* ah 4 julia julia-dataframe
我有一个如下所示的 df,我想从 df 获取字典。
\ndf = DataFrame(id=[1, 2, 3, 4], value=["Rajesh", "John", "Jacob", "sundar"], other=[0.43, 0.42,0.54, 0.63])\n\n\xe2\x94\x82 Row \xe2\x94\x82 id \xe2\x94\x82 value \xe2\x94\x82 other \xe2\x94\x82\n\xe2\x94\x82 \xe2\x94\x82 Int64 \xe2\x94\x82 String \xe2\x94\x82 Float64 \xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n\xe2\x94\x82 1 \xe2\x94\x82 1 \xe2\x94\x82 Rajesh \xe2\x94\x82 0.43 \xe2\x94\x82\n\xe2\x94\x82 2 \xe2\x94\x82 2 \xe2\x94\x82 John \xe2\x94\x82 0.42 \xe2\x94\x82\n\xe2\x94\x82 3 \xe2\x94\x82 3 \xe2\x94\x82 Jacob \xe2\x94\x82 0.54 \xe2\x94\x82\n\xe2\x94\x82 4 \xe2\x94\x82 4 \xe2\x94\x82 sundar \xe2\x94\x82 0.63 \xe2\x94\x82\nRun Code Online (Sandbox Code Playgroud)\n预期输出:
\n{1: 'Rajesh', 2: 'John', 3: 'Jacob', 4: 'sundar'}\nRun Code Online (Sandbox Code Playgroud)\n我知道如何在熊猫中做到这一点,
\ndf.set_index("id")["value"].to_dict()\nRun Code Online (Sandbox Code Playgroud)\n朱莉娅中熊猫的等效代码是什么?
\n要从数据框创建字典,您可以编写:
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]
Run Code Online (Sandbox Code Playgroud)
但是,您要求的是从向量(恰好存储在数据框中)创建字典,您可以通过以下方式执行此操作(模式非常相似,但仅应用于向量):
julia> Dict(pairs(df.value))
Dict{Int64,String} with 4 entries:
4 => "sundar"
2 => "John"
3 => "Jacob"
1 => "Rajesh"
Run Code Online (Sandbox Code Playgroud)
如果你想要一个从:id到:valuewrite 的映射(假设:id是唯一的;同样 - 它只是两个向量,它们存储在数据帧中的事实在这里并不重要):
julia> Dict(Pair.(df.id, df.value))
Dict{Int64,String} with 4 entries:
4 => "sundar"
2 => "John"
3 => "Jacob"
1 => "Rajesh"
Run Code Online (Sandbox Code Playgroud)