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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章