[DataFrames Question]: Transpose of dataframe

Question: How do I transpose a dataframe (columns become rows, rows become columns)?

There isn’t a way to do this directly. You can convert to a matrix and transpose that, but you need to deal with the column in df1 that you want to be heaters in df2, and you need to turn the headers into a column. Or do something like this (untested, and assumes your first column should become the new headers):

let df2 = DataFrame(old_headers=names(df)[2:end])
    for row in eachrow(df1)
        df2[!, Symbol(row[1])] = vec(row[2:end])
    end
    df2
end

Alternatively, something creative with pivoting should work - see the docs

1 Like

For people that find this thread searching for a way to solve this problem without having to write their own ad hoc solution, there is a solution using DataFrames.jl methods stack and unstack.

1 Like