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

Json 将数据帧中的字符串数组拆分为各自的列,json,dataframe,apache-spark,pyspark,explode,Json,Dataframe,Apache Spark,Pyspark,Explode,我有这样一个数据帧: df.show() 如何将其转换为如下所示的数据帧 +----+----+ |col1|col2| +----+----+ | a| b| | c| d| +----+----+ 这取决于“列表”的类型: 如果其类型为ArrayType(): 您可以像使用python一样使用[]访问这些值: 如果它的类型为StructType():(可能是通过读取JSON构建数据帧) 您可以使用*直接“拆分”列: 列表是固定长度的吗?谢谢,它确实

我有这样一个数据帧:

df.show()

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

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

这取决于“列表”的类型:

如果其类型为
ArrayType()

  • 您可以像使用python一样使用
    []
    访问这些值:
  • 如果它的类型为
    StructType()
    :(可能是通过读取JSON构建数据帧)
  • 您可以使用
    *
    直接“拆分”列:

列表
是固定长度的吗?谢谢,它确实是由JSON构建的,并且是ArrayType。你回答的第一部分很有帮助。但是,您的答案中的StructType,'col'列的内容不是像[(col1=a),(col2:b),(col3:c)]?@Gadam我是在现有的数据框架中创建它的。如果你看到了,这就是我访问上面这些元素的方式
+----+----+ 
|col1|col2| 
+----+----+ 
|   a|   b| 
|   c|   d|  
+----+----+ 
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]|
+---+---------+
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|
+---+------+------+------+
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|
+---+----+----+----+