Search code examples
f#deedle

F# deedle transform Series<string, obj> to Series<string, float>?


If I get a row of Frame by using the .Rows.[rowIndex] operation, Deedle will return me an Object Series. Sometimes I know this only contains float. How do i convert all the obj into float series in on shot?


Solution

  • In Deedle series are generic, so ideally it should be possible to get a float series right away. But as the reasons why you get a series of Objects is not clear, you can still convert the values to floats by mapping an appropriate type casting function:

    #load @"..\packages\Deedle.1.2.4\Deedle.fsx"
    
    open Deedle
    open System
    
    // Let's prepare a sample series
    let keys   = ["1";"2";"3"]
    let values = [1.1 :> Object;1.2 :> Object;1.3 :> Object]
    let series = Series(keys, values)
    
    // Now apply the map taking the Series<string,System.Object> series to Series<string,float>
    series |> Series.map (fun _ v -> v :?> float)
    
    // as @Foggy Finder pointed out, there is a convenience function to only map values
    series |> Series.mapValues (fun v -> v :?> float)
    
    // Alternatively, use the tryMap function that takes the Series<int,Object> series
    // to Series<int,TryValue<float>>
    series |> Series.tryMap (fun _ v -> v :?> float)
    

    The type of the Series.map function is (('a -> 'b -> 'c) -> Series<'a,'b> -> Series<'a,'c>) when 'a : equality. This means that the first argument of the mapping function is the key which we ignore using the underscore as it is not needed to make the type cast. As Foggy Finder pointed out, there is a convenience function Series.mapValues that hides the keys.