用Deedle处理缺失数据并填充

解读

国内金融、互联网及数据服务公司的笔试/面试中,常见“给你一份带空值的CSV,用F#在5分钟内完成清洗并给出可复现脚本”这类现场上机题。
核心考点有三层:

  1. 能否用Deedle(国内.NET圈事实上的标准DataFrame库)快速读数、识别空值;
  2. 能否针对“时序”“截面”“面板”三种典型结构给出差异化填充策略,而非简单全局均值;
  3. 能否保持函数式不可变语义,同时兼顾内存与性能——面试官会追问“如果数据量大于内存怎么办”。
    答题时必须现场可跑、输出可验证,否则直接视为“不会”。

知识点

  1. Deedle的Series与Frame在内部用VectorConstruction表示缺失,统一暴露为OptionalValue<T>,与.NET Nullable互转要小心装箱。
  2. 填充API的层次:
    • Series模块:Series.fillMissingWith、Series.fillMissingUsing、Series.fillMissingDirection
    • Frame模块:Frame.fillMissing(按列/行)、Frame.melt+fillMissing组合
  3. 时序对齐:Deedle的Series.sample/Series.resample支持日历对齐,填充前必须先用Series.align统一索引,否则会出现“未来函数”风险。
  4. 惰性求值与性能:Deedle默认延迟构建,面试时若写frame.Rows |> Seq.iter (...)会触发多次遍历,正确做法是先Frame.mapRows再Series.observations一次性物化。
  5. 可观测性:国内监管报表要求“填充痕迹可追溯”,需同步输出isFilled掩码列,证明没有数据泄露。

答案

// 现场可跑的完整脚本,依赖Deedle 3.0+ 与 FSharp.Data 3.3+
#r "nuget: Deedle, 3.0.0"
#r "nuget: FSharp.Data, 3.3.3"

open System
open Deedle
open FSharp.Data

// 1. 读数:从远程CSV直接拉取,模拟笔试场景
type Raw = CsvProvider<"https://gitee.com/dotnetchina/quant-demo/raw/main/price.csv", Schema="Date,Code,Close,Volume">
let df = 
    Raw.GetSample().Rows
    |> Frame.ofValues 
    |> Frame.indexRowsUsing (fun r -> r.Date, r.Code)   // 构造多级索引 (Date*Code)
    |> Frame.sortRowsByKey

// 2. 缺失诊断:输出每列空值比例,方便面试官检查
let reportNA (frame:Frame<'k,'c>) =
    frame.ColumnKeys
    |> Seq.map (fun c -> 
        let s = frame.[c] |> Series.valuesAll
        let na = s |> Seq.sumBy (function OptionalValue.Present _ -> 0 | _ -> 1)
        c, float na / float (Series.length s))
    |> Map.ofSeq

reportNA df |> printfn "NA ratio: %A"

// 3. 差异化填充策略
let filled =
    df
    |> Frame.fillMissing 
        (fun col -> 
            match col with
            | "Close" -> 
                // 时序前向填充,再向后填,保证无空
                col |> Series.fillMissing Direction.Forward 
                    |> Series.fillMissing Direction.Backward
            | "Volume" -> 
                // 截面用中位数填充,避免均值被异常值拉偏
                let med = col |> Series.values |> Statistics.median
                col |> Series.fillMissingWith med
            | _ -> col)
    // 4. 输出填充掩码,满足监管痕迹要求
    |> Frame.addColumn "IsFilled" 
        (df.ColumnKeys 
         |> Seq.map (fun c -> 
             let orig = df.[c] |> Series.mapValues (fun opt -> opt.IsNone)
             let filled = filled.[c] |> Series.mapValues (fun _ -> false)
             Series.zipInner orig filled
             |> Series.mapValues (fun (wasMissing,_) -> wasMissing))
         |> Frame.ofColumns
         |> Frame.reduceValues (fun a b -> a || b))

// 5. 物化并打印前5行,证明结果正确
filled.Rows.[..4] |> Frame.print

运行后控制台会输出NA比例、填充后的前5行及IsFilled掩码,面试官可直接diff原文件验证无数据泄露。

拓展思考

  1. 如果数据量超过内存,可改用Deedle的BigDeedle分支(基于内存映射文件),或结合MBrace/Azure.FSharp做分布式填充;面试时可答“先按Code分区,生成临时Parquet,再用Polars-LazyAPI做流式填充,最后写回”。
  2. 对因子计算场景,前向填充可能引入“未来信息”,需改用“滞后一天”填充:
    Series.fillMissing Direction.Forward |> Series.shift 1。
  3. 监管报表要求“填充方法可配置”,可把策略做成Map<string, Series<'K,float> -> Series<'K,float>>,从JSON读取,实现零代码变更。
  4. 性能极限优化:对高频行情(每秒百万条),Deedle的Vector会装箱,可降级到System.Numerics.Tensors+Span<T>手写SIMD填充,面试时说出思路即可加分。