我正在使用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] |
+----------+---------+---------+
我有办法实现这个目标吗?
答案 0 :(得分:2)
您只需将withColumn
和array
功能用作
df.withColumn("column3", array(df("columnd")))
我还看到您正在尝试将column2
从string
更改为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._