首页 > 解决方案 > 在 Julia 中将数组转换为 DataFrame 或保存为 CSV

问题描述

我的数据结构看起来类似于

tdata = Array{Int64,1}[]
# After 1st collection, push the first batch of data
push!(tdata, [1, 2, 3, 4, 5])
# After 2nd collection, push this batch of data
push!(tdata, [11, 12, 13, 14, 15])

因此,我的数据是

> tdata
2-element Array{Array{Int64,1},1}:
[1, 2, 3, 4, 5]
[11, 12, 13, 14, 15]

当我尝试将其转换为 DataFrame 时,

> convert(DataFrame, tdata)
ERROR: MethodError: Cannot `convert` an object of type Array{Array{Int64,1},1} to an object of type DataFrame

虽然我希望类似于

2×5 DataFrame
 Row │ c1     c2     c3     c4     c5    
     │ Int64  Int64  Int64  Int64  Int64 
─────┼───────────────────────────────────
   1 │     1      2      3      4      5
   2 │    11     12     13     14     15

或者,我尝试将其保存为 .CSV,但是

> CSV.write("",tdata)
ERROR: ArgumentError: 'Array{Array{Int64,1},1}' iterates 'Array{Int64,1}' values, which doesn't satisfy the Tables.jl `AbstractRow` interface

显然,我对我所拥有的数据结构有一些误解。任何建议表示赞赏!

标签: arraysdataframecsvjulia

解决方案


要么这样做:

julia> using SplitApplyCombine

julia> DataFrame(invert(tdata), :auto)
2×5 DataFrame
 Row │ x1     x2     x3     x4     x5    
     │ Int64  Int64  Int64  Int64  Int64 
─────┼───────────────────────────────────
   1 │     1      2      3      4      5
   2 │    11     12     13     14     15

或这个:

julia> DataFrame(transpose(hcat(tdata...)), :auto)
2×5 DataFrame
 Row │ x1     x2     x3     x4     x5    
     │ Int64  Int64  Int64  Int64  Int64 
─────┼───────────────────────────────────
   1 │     1      2      3      4      5
   2 │    11     12     13     14     15

或这个:

julia> DataFrame(vcat(transpose(tdata)...), :auto)
2×5 DataFrame
 Row │ x1     x2     x3     x4     x5    
     │ Int64  Int64  Int64  Int64  Int64 
─────┼───────────────────────────────────
   1 │     1      2      3      4      5
   2 │    11     12     13     14     15

或这个:

julia> df = DataFrame(["c$i" => Int[] for i in 1:5])
0×5 DataFrame

julia> foreach(x -> push!(df, x), tdata)

julia> df
2×5 DataFrame
 Row │ c1     c2     c3     c4     c5    
     │ Int64  Int64  Int64  Int64  Int64 
─────┼───────────────────────────────────
   1 │     1      2      3      4      5
   2 │    11     12     13     14     15

您的数据面临的挑战是您希望向量成为数据框的行,并且通常向量被视为数据框的列。


推荐阅读