Spark Scala 数据帧查找最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37341659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spark scala dataframe finding max
提问by G G
I am using following to find the max column value.
我正在使用以下内容来查找最大列值。
val d = sqlContext.sql("select max(date), id from myTable group By id")
How to do the same query on DataFrame without registering temp table.
如何在不注册临时表的情况下对 DataFrame 执行相同的查询。
thanks,
谢谢,
采纳答案by Carlos Vilchez
If you would like to translate that sql to code to be used with a dataframe, you could do something like:
如果您想将该 sql 转换为与数据框一起使用的代码,您可以执行以下操作:
df.groupBy("id").max("date").show()
回答by Amit_Hora
if you have a dataframe with id and date column, what you can do n spark 2.0.1 is
如果你有一个带有 id 和 date 列的数据框,你可以做的 n spark 2.0.1 是
from pyspark.sql.functions import max
mydf.groupBy('date').agg({'id':'max'}).show()
回答by Each
Direct translation to DataFrame Scala API:
直接转换为 DataFrame Scala API:
df.groupBy("id").agg(max("date"))
Spark 2.2.0 execution plan is identical for both OP's SQL & DF scenarios.
Spark 2.2.0 执行计划对于 OP 的 SQL 和 DF 场景是相同的。
Full code for spark-shell:
完整代码spark-shell:
Seq((1, "2011-1-1"), (2, "2011-1-2")).toDF("id", "date_str").withColumn("date", $"date_str".cast("date")).write.parquet("tmp")
var df = spark.read.parquet("tmp")
df.groupBy("id").agg(max("date")).explain
df.createTempView("myTable")
spark.sql("select max(date), id from myTable group By id").explain
回答by UchihaObito
For max use
最大限度地使用
df.describe(Columnname).filter("summary = 'max'").collect()[0].get(1))
And for min use
和最小使用
df.describe(Columnname).filter("summary = 'min'").collect()[0].get(1))
回答by Prashant_M
var maxValue = myTable.select("date").rdd.max()

