简体   繁体   English

根据最后一行的值按列对Deedle Frame进行排序

[英]Sorting Deedle Frame by columns based on the value of the last row

I need to sort the columns of a Deedle data frame based on the value of the last row. 我需要根据最后一行的值对Deedle数据框的列进行排序。 So the first column would have the largest value and the last column would have the smallest value in the last row. 因此,第一列的值最大,最后一列的值最小。 Deedle's Frame has most of its functionality on rows. Deedle的框架在行上具有大部分功能。

Here is some code to generate sample data where Item2 will end up with a value larger than Item1: 以下是一些代码,用于生成示例数据,其中Item2的值将大于Item1:

#load @"..\..\FSLAB\packages\FsLab\FsLab.fsx"
open System
open System.Drawing
open System.Windows.Forms
open Deedle
open FSharp.Charting
open FSharp.Charting.ChartTypes

let rnd = new System.Random()
let dateRange = [for i in 9..-1..0 ->  DateTime.Today.AddDays(float -i)]
let makeData x = [for i in 0..x-2 -> rnd.NextDouble()-0.5] |> List.scan (+) 0.
let series = makeData 10 |> List.zip <| (makeData 10 |> List.map (fun x -> x + 1.))
let df = series |> Frame.ofRecords
df?DateIndex <- dateRange |> Series.ofValues 
let df = df.IndexRows<DateTime>("DateIndex")

In this case the last row of Frame will look like this, having the larger of the values in the second column: 在这种情况下,Frame的最后一行将如下所示,在第二列中具有较大的值:
2016/05/14 0:00:00 -> 0.143158562780897 0.918480403450541

But I would like to have it in this order: 但我想按以下顺序进行:
2016/05/14 0:00:00 -> 0.918480403450541 0.143158562780897

I posted an answer but would like to see if there are other approaches as I'm not yet too familiar with Deedle. 我发布了答案,但想看看是否还有其他方法,因为我对Deedle不太熟悉。

Frame.sortRowsWith needs a sorting function: Frame.sortRowsWith需要排序功能:

let reverser (a:float) (b:float) =
    if a > b then
        -1
    else if  a < b then
        1
    else
        0

let df1 = df |> Frame.transpose
let coldIdx = df1.ColumnKeys |> Seq.max
Frame.sortRowsWith coldIdx reverser df1 |> Frame.transpose

So it transposes the data Frame, then gets the index of the last row (column in this case) and sorts the columns from the largest to smallest, finally transposing it back. 因此,它将转置数据帧,然后获取最后一行的索引(在本例中为列),并从最大到最小对列进行排序,最后将其转回。 This is handy for charting because this way the chart legends will line up with the series in the chart. 这对于制图非常方便,因为这样,图表图例将与图表中的系列对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM