Deedle Frame中基于密钥的简单查找

时间:2016-08-22 22:30:15

标签: f# deedle

假设我们有一些数据如下:

name        age   eats
bugs bunny  20    carrots
elmer fudd  50    wabbits

以下Pandas示例的Deedle等价物是什么?

>>> df[df["name"] == "bugs bunny"]["eats"]
0    carrots
Name: eats, dtype: object

>>> df[df["eats"] == "carrots"]["name"]
0    bugs bunny
Name: name, dtype: object

如果有另外一种F-sharpy方式来进行这些类型的查找(例如使用记录),这也是非常有用的。

感谢。

[编辑] 我想使用记录会如下:

type PersonRec = {name : string; age : int ; eats : string}
let rec1 = { name = "bugs bunny"; age = 20; eats = "carrots" }
let rec2 = { name = "elmer fudd"; age = 50; eats = "wabbits" }

let bugsbunnyeats =
    [rec1; rec2] 
    |> List.filter (function
                        | {name = "bugs bunny"}   -> true
                        | _                       -> false
                    )
bugsbunnyeats.Head.eats

但是如果可能的话,我仍然希望看到使用Deedle的相同操作。

2 个答案:

答案 0 :(得分:3)

Deedle有行&概念列键 - 这使得基于键执行查找变得非常容易,但是对于基于其他列/行的查找,您需要使用过滤。

给出您的样本数据:

let df = 
  frame [ 
    "age" =?> series [ "bugs bunny" => 20; "elmer fudd" => 50 ]
    "eats" =?> series [ "bugs bunny" => "carrots"; "elmer fudd" => "wabbits" ] ]

这会创建一个框架:

              age eats    
bugs bunny -> 20  carrots 
elmer fudd -> 50  wabbits 

现在您可以使用各种查找:

// Lookup using column & row keys
df.["eats", "bugs bunny"]

// Lookup using row key
df.Rows.["bugs bunny"].GetAs<int>("age")
df.Rows.["bugs bunny"]?age // for numbers

// Lookup using filtering
let carrotEaters = 
  df.Rows
  |> Series.filter (fun k row -> row.GetAs("eats") = "carrots")

carrotEaters.FirstKey() // bugs bunny
carrotEaters.FirstValue().GetAs<int>("age") // 20

答案 1 :(得分:0)

一旦你说查找,等效的数据结构就变成了地图/字典。然后你可以做一张地图地图,或者在这种情况下保持简单,记录地图。当然,Deedle将抽象大部分内容,但这里是一张地图:

type PersonRec = {Name : string; Age : int ; Eats : string}
let rec1 = { Name = "bugs bunny"; Age = 20; Eats = "carrots" }
let rec2 = { Name = "elmer fudd"; Age = 50; Eats = "wabbits" }
let recs = [rec1;rec2]
type subRec = {Age: int; Eats:string}

创建一个简单的地图:

let m1 = Map.empty<string,(int * string)>
let m1 = recs |> List.map ( fun x -> (x.Name,{subRec.Age=x.Age;subRec.Eats = x.Eats})) 
              |> Map.ofList

m1.["bugs bunny"].Eats 
//val it : string = "carrots"`

谁吃胡萝卜?

m1 |> Seq.filter (fun (KeyValue (k,v))-> v.Eats ="carrots") 
   |> Seq.map (fun x -> x.Key)
//val it : seq<string> = seq ["bugs bunny"]