AWS Glue-pySpark:将一个字符串列拆分为一个新的整数数组列



我正试图使用Glue和pySpark在AWS上执行ETL工作,但不幸的是,我对此还很陌生。

在大多数情况下,我使用粘合动态数据帧来执行应用程序映射和其他一些必须执行的转换没有任何问题。但我遇到了一个特定列的问题,必须将其从字符串转换为整数数组。在这一列value中,我们将数据类型设置为字符串,它实际上是一个转换为字符串并用空格分隔的整数数组,例如,value列中的数据项看起来像'111 222 333 444 555 666'。我必须将此列转换为整数数组,以便将我的数据转换为'[111, 222, 333, 444, 555, 666]'

如何在AWS Glue和使用pySpark中实现这一点?非常感谢您的帮助。

使用split函数将value列拆分为space,并强制转换为array<int>

  • (或(通过使用transform(From Spark-2.4)函数并将数组元素强制转换为int

Example:

df=spark.createDataFrame([('111 222 333 444 555 666',)],["value"])
df.printSchema()
#root
# |-- value: string (nullable = true)
#using split and cast as array<int>  
df.withColumn("array_int",split(col("value"),"\s+").cast("array<int>")).
show(10,False)
#using transform function
df.withColumn("array_int",expr("""transform(split(value,"\s+"), x -> int(x))""")).
show(10,False)
#+-----------------------+------------------------------+
#|value                  |array_int                     |
#+-----------------------+------------------------------+
#|111 222 333 444 555 666|[111, 222, 333, 444, 555, 666]|
#+-----------------------+------------------------------+
df.withColumn("array_int",split(col("value"),"\s+").cast("array<int>")).printSchema()
df.withColumn("array_int",expr("""transform(split(value,"\s+"), x -> int(x))""")).printSchema()    
#root
# |-- value: string (nullable = true)
# |-- array_int: array (nullable = true)
# |    |-- element: integer (containsNull = true)

最新更新