你好,
我堅持使用 scala 中的集合。我有一個這樣的清單:
val a2 = List(("Comedy",2.0,288,Some(1978)),
("Comedy",2.5,307,Some(1978)),
("Comedy",3.0,312,Some(1978)),
("Comedy",2.5,377,Some(1978)),
("Comedy",1.0,571,Some(1978)),
("Horror"," ",288,Some(1978)),
("Horror",2.5,307,Some(1978)),
("Adventure",4.0,187,Some(2003)),
("Adventure",3.0,260,Some(2003)))
我的目標是使用具有第一個和第四個值(流派和年份)的 group by 并計算第二個和第三個值。然后,應添加一個新列以生成 count_2nd/count_3rd。最終的外觀應該是這樣的:
Comedy, some(1978) -> 5, 5 , 1.0
Horror, some(1978) -> 1, 2, 0.5
Adventure, some(2003) -> 2, 2, 1.0
我試過了:
a2.flatMap(row => row._2.map( nm => (row._1,nm.rating,nm.userId,row._3)))
但 IDE 不允許添加類似 .count(i => i._2) 的內容。我想我做這件事的方式很糟糕。
資料中也應該有空值,并且在第 6 行資料中有一個空值。通過考慮空值,我希望在 count_2nd/count_3rd 中有一些不同的值。
在scala中是否可能,如果可能,我將不勝感激:)
uj5u.com熱心網友回復:
如果您需要分組 - 使用分組:
val a2: List[(String, Double, Int, Option[Int])] = List(("Comedy", 2.0, 288, Some(1978)),
("Comedy", 2.5, 307, Some(1978)),
("Comedy", 3.0, 312, Some(1978)),
("Comedy", 2.5, 377, Some(1978)),
("Comedy", 1.0, 571, Some(1978)),
("Horror", Double.NaN, 288, Some(1978)),
("Horror", 2.5, 307, Some(1978)),
("Adventure", 4.0, 187, Some(2003)),
("Adventure", 3.0, 260, Some(2003)))
val result = a2.groupBy(t => (t._1, t._4))
.view
.mapValues(lst => (lst.filter(!_._2.isNaN).length, lst.filter(!_._3.isNaN).length)) // transform grouping into tuple with needed counts
.mapValues(t => (t._1, t._2, t._1.toFloat / t._2)) // "add" 3rd column
.toMap
println(result) // prints Map((Horror,Some(1978)) -> (1,2,0.5), (Comedy,Some(1978)) -> (5,5,1.0), (Adventure,Some(2003)) -> (2,2,1.0))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459002.html
下一篇:查找兩個陣列相交的索引
