5

I have a PySpark dataframe with a column that contains comma separated values. The number of values that the column contains is fixed (say 4). Example:

+----+----------------------+
|col1|                  col2|
+----+----------------------+
|   1|val1, val2, val3, val4|
|   2|val1, val2, val3, val4|
|   3|val1, val2, val3, val4|
|   4|val1, val2, val3, val4|
+----+----------------------+

Here I want to split col2 into 4 separate columns as shown below:

+----+-------+-------+-------+-------+
|col1|  col21|  col22|  col23|  col24|
+----+-------+-------+-------+-------+
|   1|   val1|   val2|   val3|   val4|
|   2|   val1|   val2|   val3|   val4|
|   3|   val1|   val2|   val3|   val4|
|   4|   val1|   val2|   val3|   val4|
+----+-------+-------+-------+-------+

How can this be done?

2

1 Answer 1

14

I would split the column and make each element of the array a new column.

from pyspark.sql import functions as F

df = spark.createDataFrame(sc.parallelize([['1', 'val1, val2, val3, val4'], ['2', 'val1, val2, val3, val4'], ['3', 'val1, val2, val3, val4'], ['4', 'val1, val2, val3, val4']]), ["col1", "col2"])

df2 = df.select('col1', F.split('col2', ', ').alias('col2'))

# If you don't know the number of columns:
df_sizes = df2.select(F.size('col2').alias('col2'))
df_max = df_sizes.agg(F.max('col2'))
nb_columns = df_max.collect()[0][0]

df_result = df2.select('col1', *[df2['col2'][i] for i in range(nb_columns)])
df_result.show()
>>>
+----+-------+-------+-------+-------+
|col1|col2[0]|col2[1]|col2[2]|col2[3]|
+----+-------+-------+-------+-------+
|   1|   val1|   val2|   val3|   val4|
|   2|   val1|   val2|   val3|   val4|
|   3|   val1|   val2|   val3|   val4|
|   4|   val1|   val2|   val3|   val4|
+----+-------+-------+-------+-------+
Sign up to request clarification or add additional context in comments.

3 Comments

Yes! F.split() was the way to go!
Is there any way to change newly generated column names . e.g. level1, level2 etc.. instead of col1, col2
I am using this for now: df_res = df_result.toDF(*(c.replace('col2', 'level') for c in df_result.columns))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.