![](/img/trans.png)
[英]How to register Scala UDF in spark-SQL, not Spark-Scala?
[英]How to perform mathematical operation on Long and BigInt in scala in spark-sql
我有兩個不同類型的值,如下所示在spark-sql中
scala> val ageSum = df.agg(sum("age"))
ageSum: org.apache.spark.sql.DataFrame = [sum(age): bigint]
scala> val totalEntries = df.count();
scala> totalEntries
res37: Long = 45211
第一個值來自數據幀上的聚合函數,第二個值來自數據幀上的總計函數。 兩者的類型不同,因為ageSum為bigInt且totalEntries為Long。 我想對其進行數學運算。 平均值= ageSum /總條目數
scala> val mean = ageSum/totalEntries
<console>:31: error: value / is not a member of org.apache.spark.sql.DataFrame val mean = ageSum/totalEntries
我也試圖將ageSum轉換為long類型,但無法這樣做
scala> val ageSum = ageSum.longValue
<console>:29: error: recursive value ageSum needs type
val ageSum = ageSum.longValues
ageSum是一個數據框,您需要從中提取值。 一種選擇是使用first()將值作為行獲取 ,然后從行中提取值:
ageSum.first().getAs[Long](0)/totalEntries
// res6: Long = 2
如果需要更精確的值,可以使用toDouble
在除法之前進行轉換:
ageSum.first().getAs[Long](0).toDouble/totalEntries
// res9: Double = 2.5
或者,您可以將結果設為ageSum的另一列:
ageSum.withColumn("mean", $"sum(age)"/totalEntries).show
+--------+----+
|sum(age)|mean|
+--------+----+
| 10| 2.5|
+--------+----+
val df = Seq(1,2,3,4).toDF("age")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.