Canadian_Hombre
Canadian_Hombre

Reputation: 119

Handling Option values to save to .csv in F#

I am doing some data-mining using Fsharp. To ensure that no blank values occur during the datamining process I need to make sure that empty values do not make it through what I am parsing therefore I am using a double option. An masked version of the data is shown below...

type structure = {
    time: double option
    pressure: double option
    force: double option }
let rawData =
  [|  {| time = Some(15); pressure = Some(50); force = Some(100)|}
      {| time = Some(16); pressure = Some(55); force = Some(110)|}
      {| time = Some(17); pressure = None);    force = Some(110)|}
      {| time = Some(16); pressure = Some(65); force = None|}
      {| time = Some(18); pressure = Some(70); force = Some(120)|} |]

I am currently saving this into a Deedle Data frame and saving to a .csv. However when I do this the values have "Some()" associated with them. They also have blank values for the None values.

How would I be able to take the "Some()" around the numbers away and turn the None values to "NaN" then save this to a .csv?

Upvotes: 1

Views: 49

Answers (1)

Charles Roddie
Charles Roddie

Reputation: 947

How would I be able to take the "Some()" around the numbers away and turn the None values to "NaN"

Create a function with signature double option -> string. You can process an option using a match expression.

let doubleOptionToStringFlattened =
    function
    | Some(d:double) -> d.ToString()
    | None -> "NaN"

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/options

then save this to a .csv

let csvLineFromStructure(s:structure) =
    [| s.time; s.pressure; s.force |]
    |> Array.map doubleOptionToStringFlattened
    |> String.concat ","

// then create a line per structure:
let csvFromStructures(structures:structure[]) =
    structures |> Array.map csvLineFromStructure |> String.concat Environment.NewLine

Upvotes: 2

Related Questions