0

I have the below table:

+-------+---------+---------+
|movieId|movieName|    genre|
+-------+---------+---------+
|      1| example1|   action|
|      1| example1| thriller|
|      1| example1|  romance|
|      2| example2|fantastic|
|      2| example2|   action|
+-------+---------+---------+

What I am trying to achieve is to append the genre values together where the id and name are the same. Like this:

+-------+---------+---------------------------+
|movieId|movieName|    genre                  |
+-------+---------+---------------------------+
|      1| example1|   action|thriller|romance |
|      2| example2|   action|fantastic        |
+-------+---------+---------------------------+
0

1 Answer 1

2

Use groupBy and collect_list to get a list of all items with the same movie name. Then combine these to a string using concat_ws (if the order is important, first use sort_array). Small example with given sample dataframe:

val df2 = df.groupBy("movieId", "movieName")
  .agg(collect_list($"genre").as("genre"))
  .withColumn("genre", concat_ws("|", sort_array($"genre")))

Gives the result:

+-------+---------+-----------------------+
|movieId|movieName|genre                  |
+-------+---------+-----------------------+
|1      |example1 |action|thriller|romance|
|2      |example2 |action|fantastic       |
+-------+---------+-----------------------+
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.