将数据帧中的字符串数组拆分为自己的列



>我有一个这样的数据帧:

df.show((

+-----+ 
|col1 | 
+-----+ 
|[a,b]| 
|[c,d]|   
+-----+ 

如何将其转换为如下所示的数据帧

+----+----+ 
|col1|col2| 
+----+----+ 
|   a|   b| 
|   c|   d|  
+----+----+ 

这取决于您的"列表"的类型:

如果是ArrayType()类型:

df = spark.createDataFrame(spark.sparkContext.parallelize([['a', ["a","b","c"]], ['b', ["d","e","f"]]]), ["key", "col"])
df.printSchema()
df.show()
root
|-- key: string (nullable = true)
|-- col: array (nullable = true)
|    |-- element: string (containsNull = true)
+---+---------+
|key|      col|
+---+---------+
|  a|[a, b, c]|
|  b|[d, e, f]|
+---+---------+
  • 您可以使用 Python 访问这些值[]
df.select("key", df.col[0], df.col[1], df.col[2]).show()
+---+------+------+------+
|key|col[0]|col[1]|col[2]|
+---+------+------+------+
|  a|     a|     b|     c|
|  b|     d|     e|     f|
+---+------+------+------+
  • 如果它属于StructType()类型:(也许您通过读取 JSON 构建了数据帧(
df2 = df.select("key", F.struct(
df.col[0].alias("col1"), 
df.col[1].alias("col2"), 
df.col[2].alias("col3")
).alias("col"))
df2.printSchema()
df2.show()
root
|-- key: string (nullable = true)
|-- col: struct (nullable = false)
|    |-- col1: string (nullable = true)
|    |-- col2: string (nullable = true)
|    |-- col3: string (nullable = true)
+---+---------+
|key|      col|
+---+---------+
|  a|[a, b, c]|
|  b|[d, e, f]|
+---+---------+
  • 您可以使用*直接"拆分"列:
df2.select('key', 'col.*').show()
+---+----+----+----+
|key|col1|col2|col3|
+---+----+----+----+
|  a|   a|   b|   c|
|  b|   d|   e|   f|
+---+----+----+----+

最新更新