How can a string column be split by comma into a new dataframe with applied schema?
As an example, here's a pyspark DataFrame with two columns (id and value)
df = sc.parallelize([(1, "200,201,hello"), (2, "23,24,hi")]).toDF(["id", "value"])
I want to get and split the value column into a new DataFrame and apply the following schema:
from pyspark.sql.types import IntegerType, StringType, StructField, StructType
message_schema = StructType(
[
StructField("id", IntegerType()),
StructField("value", IntegerType()),
StructField("message", StringType()),
]
)
What would work is:
df_split = (
df.select(split(df.value, ",\s*"))
.rdd.flatMap(lambda x: x)
.toDF()
)
df_split.show()
But I would still need to cast and rename the columns based on the schema:
df_split.select(
[
col(_name).cast(_schema.dataType).alias(_schema.name)
for _name, _schema in zip(df_split.columns, message_schema)
]
).show()
with the expected result:
+---+-----+-------+
| id|value|message|
+---+-----+-------+
|200| 201| hello|
| 23| 24| hi|
+---+-----+-------+