f# - F#中的条件求和

标签 f# pivot record

我在 F# 中为某些客户端数据定义了一个记录类型,如下所示:-

  type DataPoint = {
       date: string; 
       dr: string; 
       Group: string; 
       Product: string; 
       Book: int; 
       Revenue: int} with 
          static member fromFile file =
               file
               |> File.ReadLines
               |> Seq.skip 1 //skip the header
               |> Seq.map (fun s-> s.Split ',') // split each line into array
               |> Seq.map (fun a -> {date = string a.[0]; dr = string a.[1];
                              Group = string a.[2]; Product = string a.[3];
                                Book = int a.[4]; Revenue = int a.[5] });;  

    // creates a record for each line
    let pivot (file) = DataPoint.fromFile file
              |> ??????????

对于 date、dr、Group 和 Product 都相等的行,我想对所有 Book 和 Revenue 条目求和,生成一个透视行。所以某种 if else 语句应该没问题。我怀疑我需要从第一个数据点开始并递归添加每个匹配的行,然后删除匹配的行以避免输出中的重复。

完成此操作后,我将能够轻松地将这些旋转的行写入另一个 csv 文件。

任何人都可以让我开始吗?

最佳答案

Seq.groupBySeq.reduce是你要找的:

let pivot file = 
    DataPoint.fromFile file
    |> Seq.groupBy (fun dp -> dp.date, dp.dr, dp.Group, dp.Product)
    |> Seq.map (snd >> Seq.reduce (fun acc dp -> 
                          { date = acc.date; dr = acc.dr; 
                            Group = acc.Group; Product = acc.Product;
                            Book = acc.Book + dp.Book; 
                            Revenue = acc.Revenue + dp.Revenue; }))

关于f# - F#中的条件求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13474223/

相关文章:

F# 区分联合 - "downcasting"到子类型

F# .NET 标准库项目

mysql - sql 合并行成列(多对多的情况)

arrays - COBOL 解串到数组中

android - 如何在Android中实现恢复/暂停录音?

Delphi:记录中的字符串大于 255 个字符

recursion - 提取列表中的两个元素并递归传递其余元素

f# - 如何做 bool 独占或?

sql - 使用多个条件多次选择单个字段

mysql - 使用 MySQL 数据透视表时的动态 AS