Can I sort a Deedle frame?

813 views Asked by At

From what I can tell a Deedle frame is only sorted by the index. Is there any way to apply a custom sorting function or sort by a given series (and define ascending/descending order)?

3

There are 3 answers

0
Gene Belitski On

Sticking to a "standard" frame of type Frame<int,string> (row index of integers and column names of strings) it is easy to implement a function capable of reordering the frame based on any single column contents in ascending or descending order:

let reorder isAscending sortColumnName (frame:Frame<int,string>)   =
    let result = frame |> Frame.indexRows sortColumnName
                       |> Frame.orderRows |> Frame.indexRowsOrdinally
    if isAscending then result else result |> Frame.mapRowKeys ((-) 0)
                                           |> Frame.orderRows
                                           |> Frame.indexRowsOrdinally

A smoke test over peopleList sample frame:

     Name    Age Countries          
0 -> Joe     51  [UK; US; UK]       
1 -> Tomas   28  [CZ; UK; US; CZ] 
2 -> Eve     2   [FR]               
3 -> Suzanne 15  [US] 

reorder false "Name" peopleList returns the frame where Name is sorted in descending order

     Name    Age Countries          
0 -> Tomas   28  [CZ; UK; US; CZ] 
1 -> Suzanne 15  [US]               
2 -> Joe     51  [UK; US; UK]       
3 -> Eve     2   [FR]

while reorder true "Age" peopleList returns the frame where Age is sorted in ascending order

     Name    Age Countries          
0 -> Eve     2   [FR]               
1 -> Suzanne 15  [US]               
2 -> Tomas   28  [CZ; UK; US; CZ] 
3 -> Joe     51  [UK; US; UK]

Nevertheless, requirement of absent duplicate values in to-be-ordered column might be considered as a showstopper for this approach to Deedle frame ordering.

0
Adam Klein On

Deedle 1.0 has additional sorting features for rows & cols

  • Frame.sortRows
  • Frame.sortRowsWith
  • Frame.sortRowsBy
0
nikiwiles On

You can sort a Deedle frame based on the values in a named column, like so:

myFrame |> Frame.sortRowsBy "columnName" (fun v -> -v) (descending)

myFrame |> Frame.sortRowsBy "columnName" (fun v -> v) (ascending)