Dataframe to csv with the index column

How to write a dataframe with the index column to a csv please? This is what I have put togeter but I am missing the index. (Btw, I dont even know if thats the best way. What I want, is to save a nested list of lists to a csv along with some identifier)

using CSV
using DataFrames

lis = [[1,2,3,4], [3], [5, 8]]
d = Dict( (i => [lis[i]] for i=1:length(lis)))
df = DataFrame(d)
df = DataFrame(Matrix(df)')
df = select(df, "x1" => "col_1")
CSV.write("df.csv", df, header=true)

A quick look at the docs and it seems like there isn’t a way to have the row number be printed. Just do

julia> insertcols!(df, 1, :Row => 1:nrow(df))
3Γ—2 DataFrame
β”‚ Row β”‚ Row   β”‚ col_1     β”‚
β”‚     β”‚ Int64 β”‚ Adjoint…  β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1   β”‚ 1     β”‚ [1 2 3 4] β”‚
β”‚ 2   β”‚ 2     β”‚ [3]       β”‚
β”‚ 3   β”‚ 3     β”‚ [5 8]     β”‚

and it will save with a column Row.

But it sounds like you are having some trouble with DataFrames constructors. Maybe do this to create your data frame

julia> d = DataFrame(Row = 1:length(lis), Value = lis)
3Γ—2 DataFrame
β”‚ Row β”‚ Row   β”‚ Value        β”‚
β”‚     β”‚ Int64 β”‚ Array…       β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1   β”‚ 1     β”‚ [1, 2, 3, 4] β”‚
β”‚ 2   β”‚ 2     β”‚ [3]          β”‚
β”‚ 3   β”‚ 3     β”‚ [5, 8]       β”‚

Thanks so much"

Also note that you can transpose a data frame using permutedims. And calling a DataFrame constructor with a Matrix is deprecated. Use DataFrame(Matrix(df)', :auto).

1 Like