Julia数据框转化为矩阵

Julia构建数据框

using DataFrames
t1 = DataFrame(y1=collect(1:3),y2=collect(4:6),y3=collect(7:9))

结果:

Main> t1 = DataFrame(y1=collect(1:3),y2=collect(4:6),y3=collect(7:9))
3×3 DataFrames.DataFrame
│ Row │ y1 │ y2 │ y3 │
├─────┼────┼────┼────┤
│ 1   │ 1  │ 4  │ 7  │
│ 2   │ 2  │ 5  │ 8  │
│ 3   │ 3  │ 6  │ 9  │

Julia构建矩阵

b = Array{Float64}(3,3)
b[:]=1:9
b

结果:

Main> b = Array{Float64}(3,3)
3×3 Array{Float64,2}:
 5.06772e-316  1.15645e-315  1.15645e-315
 1.15645e-315  1.15645e-315  1.15645e-315
 1.15645e-315  1.15645e-315  5.06774e-316

Main> b[:]=1:9
1:9

Main> b
3×3 Array{Float64,2}:
 1.0  4.0  7.0
 2.0  5.0  8.0
 3.0  6.0  9.0

对数据框进行矩阵操作, 报错

转置:

Main> t1'
ERROR: MethodError: no method matching transpose(::DataFrames.DataFrame)
Closest candidates are:
  transpose(::BitArray{2}) at linalg\bitarray.jl:265
  transpose(::Missings.Missing) at C:\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\JuliaPro-0.6.4.1\pkgs-0.6.4.1\v0.6\Missings\src\Missings.jl:92
  transpose(::Number) at number.jl:113
  ...
Stacktrace:
 [1] ctranspose(::DataFrames.DataFrame) at .\operators.jl:708
 [2] eval(::Module, ::Any) at .\boot.jl:235

对矩阵进行操作, 成功

转置:

Main> b'
3×3 Array{Float64,2}:
 1.0  2.0  3.0
 4.0  5.0  6.0
 7.0  8.0  9.0

编写函数将数据库转化为矩阵

思路:

  1. 提取数据框的行数和列数
  2. 定义相同行列的空数组
  3. 将相应的位置复制到数组中
function dataframe_2_array(dataframe)
    (a,b)=size(dataframe)
    A = Array{Float64}(a,b)
    for i in 1:a
        for j in 1:b
            A[i,j] = dataframe[i,j]
        end
    end
    return A
end

执行情况:

t2 = dataframe_2_array(t1)
t2
t2'

结果:

Main> t2 = dataframe_2_array(t1)
3×3 Array{Float64,2}:
 1.0  4.0  7.0
 2.0  5.0  8.0
 3.0  6.0  9.0

Main> t2'
3×3 Array{Float64,2}:
 1.0  2.0  3.0
 4.0  5.0  6.0
 7.0  8.0  9.0

上一篇:Julia 构建对角矩阵 diag matrix


下一篇:向MobaXterm上传本地大文件不成功怎么办?