Write CSV with columns in a specific order

Hi all,

I currently have some code which reads in a csv and does some manipulation and I want to then output my new dataframe in a specific order by column.

Currently I have column headers from the input:
Country, Region, Currency, Capital

And i would like to write these out as:

Currency, Region, Currency, Capital

Is there a way to do this within the write function?

I tried reading in the columns as I wanted them output using select but that just wrote them in the same order they were in the input.

thanks in advance!

  1. select!(df, [:Currency, :Region, :Country, :Capital])
  2. Write DataFrame to CSV

taken from How do I change the order of columns in a Julia DataFrame? - Stack Overflow after a 5 second internet search.
Does this answer your question?

If you don’t want to replace the existing DataFrame, just use select() instead of select!() and pipe it into the CSV write function.

3 Likes

…

1 Like

Sorry but the procedure just works as expected:

julia> using DataFrames

julia> df = DataFrame(a = rand(5), b = rand(5)) # create random df
5Γ—2 DataFrame
 Row β”‚ a          b
     β”‚ Float64    Float64
─────┼─────────────────────
   1 β”‚ 0.51397    0.897642
   2 β”‚ 0.242787   0.562512
   3 β”‚ 0.733361   0.68564
   4 β”‚ 0.0689889  0.59266
   5 β”‚ 0.579379   0.527535

julia> select!(df, [:b, :a]) # inplace
5Γ—2 DataFrame
 Row β”‚ b         a
     β”‚ Float64   Float64
─────┼─────────────────────
   1 β”‚ 0.897642  0.51397
   2 β”‚ 0.562512  0.242787
   3 β”‚ 0.68564   0.733361
   4 β”‚ 0.59266   0.0689889
   5 β”‚ 0.527535  0.579379

julia> select(df, [:a, :b]) # copy
5Γ—2 DataFrame
 Row β”‚ a          b
     β”‚ Float64    Float64
─────┼─────────────────────
   1 β”‚ 0.51397    0.897642
   2 β”‚ 0.242787   0.562512
   3 β”‚ 0.733361   0.68564
   4 β”‚ 0.0689889  0.59266
   5 β”‚ 0.579379   0.527535

The resulting DataFrame can simply be used in the desired CSV write function then (also available via piping/chaining) and deliver the desired results.
Maybe this more explicit example better helps OP to understand what has to be done.

4 Likes

Thanks for the replies both, I had done something silly with the dataframe and the select function worked fine!
Will get this some day :slight_smile: