从 spark 数据帧访问特定行

Access specific row from spark dataframe

我是 azure spark/databricks 的新手,正在尝试访问特定的行,例如数据框中的第 10 行。

这是我目前在笔记本上所做的

1.在 table

中读取 CSV 文件
spark.read
  .format("csv")
  .option("header", "true")
  .load("/mnt/training/enb/commonfiles/ramp.csv")
  .write
  .mode("overwrite")
  .saveAsTable("ramp_csv")

2。为 "table" ramp_csv

创建一个 DataFrame
val rampDF = spark.read.table("ramp_csv")

3。读取特定行

我在 Scala 中使用以下逻辑

val myRow1st = rampDF.rdd.take(10).last

display(myRow1st)

它应该显示第 10 行,但我收到以下错误

command-2264596624884586:9: error: overloaded method value display with alternatives:
  [A](data: Seq[A])(implicit evidence: reflect.runtime.universe.TypeTag[A])Unit <and>
  (dataset: org.apache.spark.sql.Dataset[_],streamName: String,trigger: org.apache.spark.sql.streaming.Trigger,checkpointLocation: String)Unit <and>
  (model: org.apache.spark.ml.classification.DecisionTreeClassificationModel)Unit <and>
  (model: org.apache.spark.ml.regression.DecisionTreeRegressionModel)Unit <and>
  (model: org.apache.spark.ml.clustering.KMeansModel)Unit <and>
  (model: org.apache.spark.mllib.clustering.KMeansModel)Unit <and>
  (documentable: com.databricks.dbutils_v1.WithHelpMethods)Unit
 cannot be applied to (org.apache.spark.sql.Row)
display(myRow1st)
^
Command took 0.12 seconds --

你能分享一下我在这里缺少的东西吗?我尝试了一些其他的东西,但没有用。 在此先感谢您的帮助!

以下是您的代码中发生的事情的细分:

rampDF.rdd.take(10) returns Array[Row]

.last returns Row

display() 接受一个 Dataset 而你传递给它一个 Row。您可以使用 .show(10) 以表格形式显示前 10 行。

另一种选择是 display(rampDF.limit(10))

我也同意 João 的回答。但是,如果您坚持将第 N 行作为 DataFrame 并避免收集到驱动程序节点(比如当 N 非常大时),您可以这样做:

import org.apache.spark.sql.functions._
import spark.implicits._

val df = 1 to 100 toDF //sample data
val cols = df.columns

df
.limit(10)
.withColumn("id", monotonically_increasing_id())
.agg(max(struct(("id" +: cols).map(col(_)):_*)).alias("tenth"))
.select(cols.map(c => col("tenth."+c).alias(c)):_*)

这将 return:

+-----+
|value|
+-----+
|   10|
+-----+

我也同意 João Guitana 的回答。专门获取第 10 条记录的替代方法:

val df = 1 to 1000 toDF
val tenth = df.limit(10).collect.toList.last
tenth: org.apache.spark.sql.Row = [10]

那个 return 第 10 个 Rowdf