Percy

Spark:将字符串列转换为数组

java

如何将已作为字符串读取的列转换为数组列?即从下面的模式转换

scala> test.printSchema
root
 |-- a: long (nullable = true)
 |-- b: string (nullable = true)

+---+---+
|  a|  b|
+---+---+
|  1|2,3|
+---+---+
|  2|4,5|
+---+---+

至:

scala> test1.printSchema
root
 |-- a: long (nullable = true)
 |-- b: array (nullable = true)
 |    |-- element: long (containsNull = true)

+---+-----+
|  a|  b  |
+---+-----+
|  1|[2,3]|
+---+-----+
|  2|[4,5]|
+---+-----+

如果可能,请同时共享scala和python实现。在相关说明中,从文件本身读取时如何处理它?我有约450列的数据,我想以这种格式指定的列很少。目前,我正在pyspark中阅读以下内容:

df = spark.read.format('com.databricks.spark.csv').options(
    header='true', inferschema='true', delimiter='|').load(input_file)

谢谢。


阅读 1515

收藏
2020-12-04

共1个答案

小编典典

有各种各样的方法,

最好的方法是使用split函数并强制转换为array<long>

data.withColumn("b", split(col("b"), ",").cast("array<long>"))

您也可以创建简单的udf来转换值

val tolong = udf((value : String) => value.split(",").map(_.toLong))

data.withColumn("newB", tolong(data("b"))).show

希望这可以帮助!

2020-12-04