【问题标题】:Calculating mean and standard deviation using Spark / SCALA使用 Spark / SCALA 计算平均值和标准差
【发布时间】:2023-10-03 22:35:01
【问题描述】:

我有一个数据框:

+------------------+
|         speed    |
+------------------+
|               0.0|
|               0.0|
|               0.0|
|               0.0|
|               0.0|
|               0.0|
| 3.851015222867941|
| 4.456657435740331|
|               0.0|
|               NaN|
|               0.0|
|               0.0|
|               NaN|
|               0.0|
|               0.0|
| 5.424094717765175|
|1.5781185921913181|
|2.6695439462433033|
| 17.43513658955467|
| 5.440912941359523|
|11.507138536880484|
|12.895677610360089|
| 9.930875909722456|
+------------------+

我想计算速度列的平均值和标准差。 当我执行这段代码时

dataframe_final.select("speed").orderBy("id").agg(avg("speed")).show(1000)

我明白了

+------------+
|avg(speed)|
+------------+
|         NaN|
+------------+

问题出在哪里?有没有办法解决?

谢谢

【问题讨论】:

  • agg(avg("Vitesse")) 将尝试计算VitessegroupBy 之后的列的平均值。

标签: scala apache-spark


【解决方案1】:

您的数据集中有 NaN(不是数字)值。你不能用这些计算平均值。

要么过滤它们:


dataframe_final
  .filter($"speed".isNotNull())
  .select("speed")
  .orderBy("id")
  .agg(avg("speed"))
  .show(1000)

或者使用fill function 将它们替换为0

dataframe_final
  .select("speed")
  .na.fill(0)
  .agg(avg("speed"))
  .show(1000)

此外,您正在尝试聚合 Vitesse 列而不是 speed

【讨论】:

  • 谢谢@nathan_gs。如何将 'Nan' 值替换为 0 ?
  • 将此添加到答案@HaJar
【解决方案2】:
we can also createOrReplaceTempView(dataframe_final) and then we can use spark sql to query and take avg of the speed column

val tableview= dataframe_final.createOrReplaceTempView()
val query = select avg(speed) from tableview where speed IS NOT NULL order by Id
spark.sql(query).show()

【讨论】: