arrays - 在 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
显然,我对我所拥有的数据结构有一些误解。任何建议表示赞赏!
解决方案
要么这样做:
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
您的数据面临的挑战是您希望向量成为数据框的行,并且通常向量被视为数据框的列。
推荐阅读
- python-3.x - 为什么使用 SQLAlchemy,在 MariaDB 10.3.17 上的 JSON col 中插入没有 ASCII 的行会引发 UnicodeEncodeError?
- node.js - Cloudinary 上传图像不起作用(反应本机和节点
- python - Python字典中访问键值对的问题
- python - 如何使 to_sql 命令的 dtype 参数从字典中提取
- c# - 使用 Code First EF 6.4.4 的第一个应用程序:SQL Server 连接错误
- wordpress - 如何删除wordpress自定义通知?
- firebase-realtime-database - Firebase 实时数据库 - 规则
- string - 在最新的 Powershell 7.x 中将两个字符插入 GB UTF8 字符串的最快方法
- javascript - 从 JavaScript 数组中包含的对象中删除交替逗号
- javascript - 单击时网格中的元素会移动