如何将JuMP值中的数组添加到数据框中的列

问题描述

我有这个数组,需要基于该数组创建一个数据框

getvalue.(W)
1-dimensional DenseAxisArray{Float64,1,...} with index sets:
    Dimension 1,0:6
And data,a 7-element Array{Float64,1}:
 80.0
 65.0
 65.0
 65.0
 65.0
 65.0
 65.0

尝试时出现此错误

df=DataFrame(W=getvalue.(W)[1:6])

KeyError: key 1:6 not found

解决方法

您需要在collect上进行DenseAxisArray

重新创建数据:

julia> using JuMP,DataFrames

julia> vv = JuMP.Containers.DenseAxisArray([80.,65.,65.],0:6)
1-dimensional DenseAxisArray{Float64,1,...} with index sets:
    Dimension 1,0:6
And data,a 7-element Array{Float64,1}:
 80.0
 65.0
 65.0
 65.0
 65.0
 65.0
 65.0

将数据放入数据框:

julia> DataFrame(vv=collect(vv)[1:6])
6×1 DataFrame
│ Row │ vv      │
│     │ Float64 │
├─────┼─────────┤
│ 1   │ 80.0    │
│ 2   │ 65.0    │
│ 3   │ 65.0    │
│ 4   │ 65.0    │
│ 5   │ 65.0    │
│ 6   │ 65.0    │

如果您的vv很大,那么您也可以使用稍长的代码来节省时间和内存(结果将是相同的):

DataFrame(vv=[vv[CartesianIndex(i)] for i in 1:6])