从DF中的现有属性值添加Array [long]类型的属性

时间:2017-06-19 11:53:54

标签: scala apache-spark dataframe apache-spark-sql

我正在使用spark 2.0并且有一个用例,我需要将列的属性类型从string转换为Array [long]。

假设我有一个带架构的数据框:

root
 |-- unique_id: string (nullable = true)
 |-- column2 : string (nullable = true)

DF:

+----------+---------+
|unique_id | column2 |
+----------+---------+
|  1       |  123    |
|  2       |  125    |
+----------+---------+

现在我想添加一个名为“column3”的新列,其类型为Array [long],其值​​为“column2” 喜欢:

root
 |-- unique_id: string (nullable = true)
 |-- column2: long (nullable = true)
 |-- column3: array (nullable = true)
 |    |-- element: long (containsNull = true)

新DF:

+----------+---------+---------+
|unique_id | column2 | column3 |
+----------+---------+---------+
|  1       |  123    | [123]   | 
|  2       |  125    | [125]   |
+----------+---------+---------+

我有办法实现这个目标吗?

1 个答案:

答案 0 :(得分:2)

您只需将withColumnarray功能用作

即可
df.withColumn("column3", array(df("columnd")))

我还看到您正在尝试将column2string更改为Long。一个简单的udf函数应该可以解决问题。所以最终的解决方案是

def changeToLong = udf((str: String) => str.toLong)


val finalDF = df
  .withColumn("column2", changeToLong(col("column2")))
  .withColumn("column3", array(col("column2")))

您还需要导入functions

import org.apache.spark.sql.functions._