Sort Julia DataFrame in descending Order

646 Views Asked by At

I have a DataFrame

using DataFrames
using DataFramesMeta
using Chain

df = DataFrame(a=1:3,b=4:6)

that I want to sort descending by column :a. Doing it ascending is intuitive...

@chain df begin
    @orderby(:a)
end

How can I do this?

Looking for different solutions here, but specifically for a solution that can be used in @chains.

2

There are 2 best solutions below

0
On

So, if you have a numeric column, you can simply negate it...

using DataFrames
using DataFramesMeta
using Chain

df = DataFrame(a=1:3,b=4:6)

@chain df begin
    @orderby(-:a)
end

But this logic doesn't work for Dates for example.

2
On

You can just use sort with rev=true:

julia> @chain df begin
           sort(:a, rev=true)
       end
3×2 DataFrame
 Row │ a      b
     │ Int64  Int64
─────┼──────────────
   1 │     3      6
   2 │     2      5
   3 │     1      4

Example for multiple columns that uses order, see also docstring of sort and https://bkamins.github.io/julialang/2021/03/12/sorting.html:

julia> df = DataFrame(a=rand(Bool, 10), b=rand(Bool, 10))
10×2 DataFrame
 Row │ a      b
     │ Bool   Bool
─────┼──────────────
   1 │ false   true
   2 │  true  false
   3 │  true   true
   4 │ false   true
   5 │ false   true
   6 │ false  false
   7 │ false  false
   8 │  true  false
   9 │  true   true
  10 │  true  false

julia> sort(df, [order(:a, rev=true), :b])
10×2 DataFrame
 Row │ a      b
     │ Bool   Bool
─────┼──────────────
   1 │  true  false
   2 │  true  false
   3 │  true  false
   4 │  true   true
   5 │  true   true
   6 │ false  false
   7 │ false  false
   8 │ false   true
   9 │ false   true
  10 │ false   true