# 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], , [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")
``````

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     │ [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     │ [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
{"ft_lang_label":"__label__en","ft_lang_prob":0.84023035,"math_prob":0.9511891,"size":474,"snap":"2022-05-2022-21","text_gpt3_token_len":147,"char_repetition_ratio":0.108510636,"word_repetition_ratio":0.0,"special_character_ratio":0.34177214,"punctuation_ratio":0.15044248,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9922439,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-29T01:16:13Z\",\"WARC-Record-ID\":\"<urn:uuid:08649103-7aa6-4602-9044-4a4e4ca3bb15>\",\"Content-Length\":\"27251\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:a38e38cf-a3d7-4e26-b3dc-f321cbfad3c0>\",\"WARC-Concurrent-To\":\"<urn:uuid:1e1b1f3c-15b1-4db8-ae70-2ce6e1fde0e6>\",\"WARC-IP-Address\":\"64.71.144.205\",\"WARC-Target-URI\":\"https://discourse.julialang.org/t/dataframe-to-csv-with-the-index-column/50400\",\"WARC-Payload-Digest\":\"sha1:MBMW65EI4HWDA4PODKEZFM7WDFIJEOJX\",\"WARC-Block-Digest\":\"sha1:T2KB6K2J7FPAEQNDKUZN5XUAROMGGY7K\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652663035797.93_warc_CC-MAIN-20220529011010-20220529041010-00273.warc.gz\"}"}