【问题标题】:Single column delimited string rdd to correctly columned dataframe单列分隔字符串 rdd 到正确列的数据框
【发布时间】:2018-08-22 13:13:31
【问题描述】:

我有一个只有一列的 rdd。每列都是一个字符串,表示由| 分隔的条目列表。例如:

  col_1
 a|b|c|d
 q|w|e|r

我想把它转成dataframe,所以是这样的:

col_1 | col_2 | col_3 | col_4
 a        b       c        d
 q        w       e        r

列数未知,并且不需要标题(它们可以只是默认的列名)。

我试过了:

.map(i => i.split("|")).toDF()

但是,这只是返回一个作为值数组的列,而不是实际拆分为列。这样做的最终目标是将其写入镶木地板文件。

一种解决方案是将其写入文本文件,然后使用 Spark 将其作为带有我给定分隔符的 csv 读取,然后将其写入 parquet 文件。但这是一种糟糕的方法,必须有更好的方法来做到这一点。

【问题讨论】:

  • 输入是RDD还是DataFrame
  • @TzachZohar 输入是一个 RDD。

标签: scala apache-spark


【解决方案1】:

DataFrame 必须具有预定义的架构,因此您必须以某种方式提供列数。如果不同的记录可能有不同数量的分隔符,您必须扫描数据两次(一次确定列,然后一次转换为 DataFrame);否则 - “窥视”第一条记录可能就足够了:

import spark.implicits._

// note the necessary escaping because | is a special character in regular expressions
val arrays = rdd.map(_.split("\\|")) 

// if not all values have the same number of delimiters:
val maxCols = arrays.map(_.length).max()

// otherwise - can use first record to determine number of columns:
val maxCols = arrays.first().length

// now we create a column per (1 .. maxCols) and select these:
val result = arrays.toDF("arr")
  .select((0 until maxCols).map(i => $"arr"(i).as(s"col_$i")): _*)

result.show()
+-----+-----+-----+-----+
|col_0|col_1|col_2|col_3|
+-----+-----+-----+-----+
|    a|    b|    c|    d|
|    q|    w|    e|    r|
+-----+-----+-----+-----+

【讨论】:

  • 我真的很喜欢这个,这些东西让我们了解了 SPARK / SCALA 的力量。你很漂亮
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2018-09-29
  • 2020-09-20
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多