如何从Apache Spark / Scala中的Wrapped Array中获取数据

时间:2018-01-10 20:25:13

标签: scala apache-spark

我有一个Dataframe,其行如下所示:

[WrappedArray(1, 5DC7F285-052B-4739-8DC3-62827014A4CD, 1, 1425450997, 714909, 1425450997, 714909, {}, 2013, GAVIN, ST LAWRENCE, M, 9)]
[WrappedArray(2, 17C0D0ED-0B12-477B-8A23-1ED2C49AB8AF, 2, 1425450997, 714909, 1425450997, 714909, {}, 2013, LEVI, ST LAWRENCE, M, 9)]
[WrappedArray(3, 53E20DA8-8384-4EC1-A9C4-071EC2ADA701, 3, 1425450997, 714909, 1425450997, 714909, {}, 2013, LOGAN, NEW YORK, M, 44)]
...

一年之前的一切(本例中为2013年)都是废话,应该删除。我想将数据映射到我创建的Name类,并将其放入新的数据框中。

如何获取数据并进行映射?

这是我的Name课程:

case class Name(year: Int, first_name: String, county: String, sex: String, count: Int)

基本上,我想根据Name类的模式用行和列填充我的数据帧。我知道如何做这部分,但我只是不知道如何获取数据框中的数据。

1 个答案:

答案 0 :(得分:0)

假设数据是这样的字符串数组:

val df = Seq(Seq("1", "5DC7F285-052B-4739-8DC3-62827014A4CD", "1", "1425450997", "714909", "1425450997", "714909", "{}", "2013", "GAVIN", "STLAWRENCE", "M", "9"),
    Seq("2", "17C0D0ED-0B12-477B-8A23-1ED2C49AB8AF", "2", "1425450997", "714909", "1425450997", "714909", "{}", "2013", "LEVI", "ST LAWRENCE", "M", "9"),
    Seq("3", "53E20DA8-8384-4EC1-A9C4-071EC2ADA701", "3", "1425450997", "714909", "1425450997", "714909", "{}", "2013", "LOGAN", "NEW YORK", "M", "44"))
  .toDF("array")

您可以使用返回案例类的UDF,也可以多次使用withColumn。后者应该更有效率,可以这样做:

val df2 = df.withColumn("year", $"array"(8).cast(IntegerType))
  .withColumn("first_name", $"array"(9))
  .withColumn("county", $"array"(10))
  .withColumn("sex", $"array"(11))
  .withColumn("count", $"array"(12).cast(IntegerType))
  .drop($"array")
  .as[Name]

这会给你一个DataSet[Name]

+----+----------+-----------+---+-----+
|year|first_name|county     |sex|count|
+----+----------+-----------+---+-----+
|2013|GAVIN     |STLAWRENCE |M  |9    |
|2013|LEVI      |ST LAWRENCE|M  |9    |
|2013|LOGAN     |NEW YORK   |M  |44   |
+----+----------+-----------+---+-----+

希望它有所帮助!