将Array [String]的Spark列拆分为String列

时间:2018-02-09 08:09:40

标签: arrays string apache-spark split

如果我有一个包含Array [String]列的Dataframe:

scala> y.show
+---+----------+
|uid|event_comb|
+---+----------+
|  c|  [xx, zz]|
|  b|  [xx, xx]|
|  b|  [xx, yy]|
|  b|  [xx, zz]|
|  b|  [xx, yy]|
|  b|  [xx, zz]|
|  b|  [yy, zz]|
|  a|  [xx, yy]|
+---+----------+

如何将列"event_comb"拆分为两列(例如"event1""event2")?

1 个答案:

答案 0 :(得分:0)

如果列类型为list或Map,则可以使用getItem函数获取值

getItem(Object key)

  

获取位置的项目的表达式   从数组中取出序数,或者通过MapType中的键键获取值。

val data = Seq(
    ("c", List("xx", "zz")),
  ("b", List("xx", "xx")),
  ("b", List("xx", "yy")),
  ("b", List("xx", "zz")),
  ("b", List("xx", "yy")),
  ("b", List("xx", "zz")),
  ("b", List("yy", "zz")),
  ("a", List("xx", "yy"))
  ).toDF("uid", "event_comb")

  data.withColumn("event1", $"event_comb".getItem(0))
      .withColumn("event2", $"event_comb".getItem(1))
      .show(false)

输出:

+---+----------+------+------+
|uid|event_comb|event1|event2|
+---+----------+------+------+
|c  |[xx, zz]  |xx    |zz    |
|b  |[xx, xx]  |xx    |xx    |
|b  |[xx, yy]  |xx    |yy    |
|b  |[xx, zz]  |xx    |zz    |
|b  |[xx, yy]  |xx    |yy    |
|b  |[xx, zz]  |xx    |zz    |
|b  |[yy, zz]  |yy    |zz    |
|a  |[xx, yy]  |xx    |yy    |
+---+----------+------+------+