Reputation: 3024
I have a dataframe like this:
df.show()
+-----+
|col1 |
+-----+
|[a,b]|
|[c,d]|
+-----+
How to convert it into a dataframe like below
+----+----+
|col1|col2|
+----+----+
| a| b|
| c| d|
+----+----+
Upvotes: 1
Views: 55
Reputation: 7419
It depends on the type of your "list":
If it is of type 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]|
+---+---------+
[]
: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()
: (maybe you built your dataframe by reading a 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|
+---+----+----+----+
Upvotes: 2