0

I have the following Spark dataframe in Scala:

+---------+--------------------+--------------------+--------------------+
|       id|           col_str_1|           col_str_2|            col_list|
+---------+--------------------+--------------------+--------------------+
|        1|                   A|                   C|              [E, F]|
|        2|                   B|                   D|              [G, H]|
+---------+--------------------+--------------------+--------------------+

Where col_str_1 and col_str_2 are of type Stirng, and col_list is of type List[String].

I want a way to transform this dataframe into the following:

+---------+--------------------+
|       id|            col_list|
+---------+--------------------+
|        1|        [E, F, A, C]|
|        2|        [G, H, B, D]|
+---------+--------------------+

Any idea? Thank you.

1 Answer 1

2

You can use concat to append elements to the array column:

val df2 = df.select(
    col("id"), 
    concat(
        col("col_list"), 
        array(col("col_str_1"), col("col_str_2"))
    ).as("col_list")
)

df2.show
+---+------------+
| id|    col_list|
+---+------------+
|  1|[E, F, A, C]|
|  2|[G, H, B, D]|
+---+------------+
Sign up to request clarification or add additional context in comments.

Comments

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.