[英]Access specific row from spark dataframe
我是 azure spark/databricks 的新手,並試圖訪問特定行,例如 dataframe 中的第 10 行。
到目前為止,這是我在筆記本上所做的
1.在一個表中讀取一個CSV文件
spark.read
.format("csv")
.option("header", "true")
.load("/mnt/training/enb/commonfiles/ramp.csv")
.write
.mode("overwrite")
.saveAsTable("ramp_csv")
2.為“表”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$1: 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)
返回Array[Row]
.last
返回Row
display()
接受一個Dataset
並且你傳遞給它一個Row
。 您可以使用.show(10)
以表格形式顯示前 10 行。
另一種選擇是做display(rampDF.limit(10))
我也會用 João 的回答 go 。 但是,如果您堅持將第 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)):_*)
這將返回:
+-----+
|value|
+-----+
| 10|
+-----+
我還用 João Guitana 的回答 go。 獲得第 10 條記錄的替代方法:
val df = 1 to 1000 toDF
val tenth = df.limit(10).collect.toList.last
tenth: org.apache.spark.sql.Row = [10]
這將返回該df
的第10 Row
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.