代码之家  ›  专栏  ›  技术社区  ›  Richard

如何将字典列表转换为数据帧?

  •  0
  • Richard  · 技术社区  · 6 年前

    我有一个字典列表,其格式与下面类似。名单 列表及其目录的存在可以被视为一个给定值。

    dictlist=[]
    for i in 1:20
      push!(dictlist, Dict(:a=>i, :b=>2*i))
    end
    

    0 回复  |  直到 6 年前
        1
  •  5
  •   Frames Catherine White    6 年前

    你可以 push!

    根据 docs on row by row construction.

    正如文档所说,这比逐列构造要慢得多,但并不比自己从dicts构造列慢。

    df = DataFrame()
    for row in dictlist
        push!(df, row)
    end
    

    有一个 current proposal Vector{Dict} 一张桌子。jl行表类型。 那你就可以这么做了

    df = DataFrame(dictlist)
    
        2
  •  2
  •   kmsquire    6 年前

    DataFrame 像这样,您可以首先将其转换为 NamedTuples

    julia> using DataFrames
    
    julia> dictlist=[]
    0-element Array{Any,1}
    
    julia> for i in 1:20
             push!(dictlist, Dict(:a=>i, :b=>2*i))
           end
    
    julia> DataFrame([NamedTuple{Tuple(keys(d))}(values(d)) for d in dictlist])
    20×2 DataFrame
    │ Row │ a     │ b     │
    │     │ Int64 │ Int64 │
    ├─────┼───────┼───────┤
    │ 1   │ 1     │ 2     │
    │ 2   │ 2     │ 4     │
    │ 3   │ 3     │ 6     │
    │ 4   │ 4     │ 8     │
    │ 5   │ 5     │ 10    │
    │ 6   │ 6     │ 12    │
    │ 7   │ 7     │ 14    │
    │ 8   │ 8     │ 16    │
    │ 9   │ 9     │ 18    │
    │ 10  │ 10    │ 20    │
    │ 11  │ 11    │ 22    │
    │ 12  │ 12    │ 24    │
    │ 13  │ 13    │ 26    │
    │ 14  │ 14    │ 28    │
    │ 15  │ 15    │ 30    │
    │ 16  │ 16    │ 32    │
    │ 17  │ 17    │ 34    │
    │ 18  │ 18    │ 36    │
    │ 19  │ 19    │ 38    │
    │ 20  │ 20    │ 40    │
    

    请注意,就在今天,我将此作为 issue in Tables.jl ,因此可能很快会有更好的支持。

        3
  •  0
  •   Richard    6 年前

    此功能提供了一种可能的解决方案:

    using DataFrames
    
    function DictionariesToDataFrame(dictlist)
      ret = Dict()                 #Holds dataframe's columns while we build it
      #Get all unique keys from dictlist and make them entries in ret
      for x in unique([y for x in [collect(keys(x)) for x in dictlist] for y in x])
        ret[x] = []
      end
      for row in dictlist          #Loop through each row
        for (key,value) in ret     #Use ret to check all possible keys in row
          if haskey(row,key)       #Is key present in row?
            push!(value, row[key]) #Yes
          else                     #Nope
            push!(value, nothing)  #So add nothing. Keeps columns same length.
          end
        end
      end
      #Fix the data types of the columns
      for (k,v) in ret                             #Consider each column
        row_type = unique([typeof(x) for x in v])  #Get datatypes of each row
        if length(row_type)==1                     #All rows had same datatype
          row_type = row_type[1]                   #Fetch datatype
          ret[k]   = convert(Array{row_type,1}, v) #Convert column to that type
        end
      end
      #DataFrame is ready to go!
      return DataFrames.DataFrame(ret)
    end
    
    #Generate some data
    dictlist=[]
    for i in 1:20
      push!(dictlist, Dict("a"=>i, "b"=>2*i))
      if i>10
        dictlist[end-1]["c"]=3*i
      end
    end
    
    DictionariesToDataFrame(dictlist)
    
        4
  •  0
  •   Bill Antonello    6 年前

    对于可能稀疏的帧,这里有一个不会丢失数据,但会添加丢失的数据:

    using DataFrames
    
    dictlist = [Dict("a" => 2), Dict("a" => 5, "b" => 8)]
    
    keycol = unique(mapreduce(x -> collect(keys(x)), vcat, dictlist))
    
    df = DataFrame()
    
    df[!, Symbol("Keys")] = keycol
    
    for (i, d) in enumerate(dictlist)
        df[!, Symbol(string(i))] = [get(d, k, missing) for k in keycol]
    end
    
    println(df)
    
        5
  •  0
  •   DataPsycho    6 年前

    仅作为参考,它的外观没有任何方法可用于将dict列表转换为数据帧。相反,我们将dict列表转换为dict of list。我是说从 [(:a => 1, :b =>2), (:a => 3, :b =>4)] (:a => [1, 3], :b => [2, 4])

    function to_dict_of_array(data::Array, fields::Array)
        # Pre allocate the array needed for speed up in case of large dataset
        doa = Dict(Symbol(field) => Array{Any}(undef, length(data)) for field in fields)
        for (i, datum) in enumerate(data)
            for fn in fields
                sym_fn = Symbol(fn)
                doa[sym_fn][i]  = datum[fn]
            end
        end
        return doa
    end
    

    然后我们可以使用该方法创建数据帧。

    array_of_dict = [Dict("a" => 1, "b" =>2), Dict("a" => 3, "b" =>4)]
    required_field = ["a", "b"]
    df = DataFrame(to_dict_of_array(array_of_dict, required_field));
    

    推荐文章