【问题标题】:How can I arrange the rows and the columns in Spark using scala [duplicate]如何使用scala在Spark中排列行和列[重复]
【发布时间】:2018-09-29 18:17:45
【问题描述】:

我想要一个文本文件格式:

first line
column1;column2;column3
column1;column2;column3
last line

将其转换为没有第一行和最后一行的DataFrame 我跳过了第一行和最后一行,但随后我成为一行和一列中的其余文本 如何排列行? 我的 DataFrame 也有一个架构

var textFile = sc.textFile("*.txt")
val header = textFile.first()
val total = textFile.count()
var rows = textFile.zipWithIndex().filter(x => x._2 < total - 1).map(x => x._1).filter(x => x !=  header)

val schema = StructType(Array(
  StructField("col1", IntegerType, true),
  StructField("col2", StringType, true),
  StructField("col3", StringType, true),
  StructField("col4", StringType, true)
))

【问题讨论】:

  • 你应该用 ; 分割其余的文本。然后将它们转换为行并应用架构来创建数据框
  • 是的,我已经做到了:import spark.implicits._ val rowss = rows.map(x => {val m = x.split(","); Row(m(0) , m(1), m(2), m(3))}) val df = rowss.toDF().show() 但 toDF() 不起作用..
  • 您的数据包含 ;而不是,
  • 与 ;仍然无法正常工作我也尝试使用 spark.createDataFrame(rowRDD, schema),但我变成了很多错误

标签: scala apache-spark dataframe text rows


【解决方案1】:

您应该执行以下操作(为清楚起见,请注释)

//creating schema
import org.apache.spark.sql.types._
val schema = StructType(Array(
  StructField("col1", StringType, true),
  StructField("col2", StringType, true),
  StructField("col3", StringType, true)
))

//reading text file and finding total lines
val textFile = sc.textFile("*.txt")
val total = textFile.count()

//indexing lines for filtering the first and the last lines
import org.apache.spark.sql.Row
val rows = textFile.zipWithIndex()
    .filter(x => x._2 != 0 && x._2 < total - 1)
  .map(x => Row.fromSeq(x._1.split(";").toSeq))   //converting the lines to Row of sequences

//finally creating dataframe
val df = sqlContext.createDataFrame(rows, schema)
df.show(false)

这应该给你

+-------+-------+-------+
|col1   |col2   |col3   |
+-------+-------+-------+
|column1|column2|column3|
|column1|column2|column3|
+-------+-------+-------+

【讨论】:

  • 它工作正常,谢谢!
猜你喜欢
  • 2019-02-23
  • 2019-08-16
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 2018-02-12
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多