fslaborg / Deedle

Easy to use .NET library for data and time series manipulation and for scientific programming
http://fslab.org/Deedle/
BSD 2-Clause "Simplified" License
937 stars 195 forks source link

Create a DataFrame from a Sql.Data.DataTable? #484

Closed ghost closed 4 years ago

ghost commented 4 years ago

All,

I am looking for a way to convert from Sql.Data.DataTable into the Deedle DataFrame. This should be relatively straight forward but I can't seem to find any documentation on it.

Thanks.

zyzhu commented 4 years ago

See below a code snippet I came up with

#I "../packages/Deedle.2.1.0"
#load "Deedle.fsx"
#r "System.Data.DataSetExtensions"
open Deedle
open System.Data
open System.Linq

// Prepare dummy data
let dt = new DataTable("Customers");  
let col = dt.Columns.Add("Id", typeof<int>)
col.AllowDBNull <- false;  
col.Unique <- true;  
dt.Columns.Add("LastName", typeof<string>)
dt.Columns.Add("FirstName", typeof<string>)
for i in [0..9] do
    let row = dt.NewRow()
    row.[0] <- i
    row.[1] <- "LastName" + i.ToString()
    row.[2] <- "FirstName" + i.ToString()
    dt.Rows.Add(row)

// Create frame
let cols = dt.Columns.Cast<DataColumn>() |> Seq.map(fun x -> x.ColumnName)
let data =
    dt.AsEnumerable()
    |> Seq.map(fun x ->
        x.Field<int>(0),
        x.Field<string>(1),
        x.Field<string>(2) )
    |> Series.ofValues
let df =
    ["dt", data]
    |> frame
    |> Frame.expandCols ["dt"]
    |> Frame.indexColsWith cols

// If you'd like to index with Id column
let dfNew = df |> Frame.indexRowsInt "Id"
zyzhu commented 4 years ago

I suggest you ask future questions on StackOverflow with deedle and fsharp in the tag. The question will be more visible to other users than this repo.