Question about transpose dataframe?

Dear all,

How to transpose the dataframe below,

julia> df
3×7 DataFrame
 Row │ year    2000   2001   2002   2003   2004   2005
     │ String  Int64  Int64  Int64  Int64  Int64  Int64
─────┼──────────────────────────────────────────────────
   1 │ x         317    314    306    304    292    275
   2 │ y         766    779    808    785    794    799
   3 │ z         679    686    697    688    704    699

And I want to transpose it to

 Row │ year   x      y      z
     │ Int64  Int64  Int64  Int64
─────┼────────────────────────────
   1 │  2000    317    766    679
   2 │  2001    314    779    686
   3 │  2002    306    808    697
   4 │  2003    304    785    688
   5 │  2004    292    794    704
   6 │  2005    275    799    699

I try to use permutedims, but it gets an error.

julia> permutedims!(df, 1)
ERROR: MethodError: no method matching permutedims!(::DataFrame, ::Int64)
Closest candidates are:
  permutedims!(::Any, ::AbstractArray, ::Any) at /Applications/Julia-1.7.app/Contents/Resources/julia/share/julia/base/permuteddimsarray.jl:204
Stacktrace:
 [1] top-level scope
   @ REPL[247]:1

Here is my solution, but a little complex.

julia> df = CSV.read("d51.txt", DataFrame)
3×6 DataFrame
 Row │ 2000   2001   2002   2003   2004   2005
     │ Int64  Int64  Int64  Int64  Int64  Int64
─────┼──────────────────────────────────────────
   1 │   317    314    306    304    292    275
   2 │   766    779    808    785    794    799
   3 │   679    686    697    688    704    699

julia> year = parse.(Int, names(df))
6-element Vector{Int64}:
 2000
 2001
 2002
 2003
 2004
 2005

julia> data = hcat(year, Matrix(df)')
6×4 Matrix{Int64}:
 2000  317  766  679
 2001  314  779  686
 2002  306  808  697
 2003  304  785  688
 2004  292  794  704
 2005  275  799  699

julia> df = DataFrame(data, ["year", "x", "y", "z"])
6×4 DataFrame
 Row │ year   x      y      z
     │ Int64  Int64  Int64  Int64
─────┼────────────────────────────
   1 │  2000    317    766    679
   2 │  2001    314    779    686
   3 │  2002    306    808    697
   4 │  2003    304    785    688
   5 │  2004    292    794    704
   6 │  2005    275    799    699

permutedims works, the ! usually means in-place which isn’t possible here.

1 Like

Thanks very much. It works well.