嗨,我正在嘗試從這個 tsv 集計算電影結果的平均值
running time Genre
1 Documentary,Short
5 Animation,Short
4 Animation,Comedy,Romance
影片是一種型別,短片、喜劇、愛情片也是如此
我是 Scala 的新手,我很困惑如何在沒有任何不可變函式的情況下使用 Scala 獲得每個流派的平均值
我嘗試使用下面的代碼片段來嘗試某種迭代并根據每種型別獲取運行時間
val a = list.foldLeft(Map[String,(Int)]()){
case (map,arr) =>{
map (arr.genres.toString ->(arr.runtimeMinutes))
}}
有沒有辦法計算平均值
uj5u.com熱心網友回復:
假設資料已經被決議為如下內容:
final case class Row(runningTime: Int, genres: List[String])
然后,您可以遵循宣告式方法來計算所需的結果。
List[Row]將 a 展平成對串列,其中第一個元素是流派,第二個元素是運行時間。- 收集相同型別的所有運行時間。
- 減少每個組以計算其平均值。
def computeAverageRunningTimePerGenre(data: List[Row]): Map[String, Double] =
data.flatMap {
case Row(runningTime, genres) =>
genres.map(genre => genre -> runningTime)
}.groupMap(_._1)(_._2).view.mapValues { runningTimes =>
runningTimes.sum.toDouble / runningTimes.size.toDouble
}.toMap
注意:有一些方法可以加快速度,但恕我直言,最好先從最易讀的替代方案開始,然后在需要時重構為更高性能的方案。
您可以在此處看到運行的代碼。
uj5u.com熱心網友回復:
您可以非常簡單地使用 SQL 函式來完成此操作。首先分解每一行,使其包含每個流派的單個值,然后按它分組并計算平均值。
import sparkSession.implicits._
import org.apache.spark.sql.functions._
val xs =
Seq((1, Seq("Documentary", "Short")), (5, Seq("Animation", "Short")), (4, Seq("Animation", "Comedy", "Romance")))
.toDF("runningTime", "genres")
val ys = xs
.select('runningTime, explode('genres) as "genre")
.groupBy('genre)
.agg(avg('runningTime) as "averageRunningTime")
xs.show(false)
ys.show(false)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/339693.html
標籤:斯卡拉
下一篇:spark檢測并提取列值中的模式
