2

Simply, let's say I had the following DataFrame:

+-------------+----------+------+
|employee_name|department|salary|
+-------------+----------+------+
|        James|     Sales|  3000|
|      Michael|     Sales|  4600|
|       Robert|     Sales|  4100|
|        Maria|   Finance|  3000|
|        James|     Sales|  3000|
|        Scott|   Finance|  3300|
|          Jen|   Finance|  3900|
|         Jeff| Marketing|  3000|
|        Kumar| Marketing|  2000|
|         Saif|     Sales|  4100|
+-------------+----------+------+

How could I group by department and get all other values into a list, as follows:

department employee_name salary
Sales [James, Michael, Robert, James, Saif] [3000, 4600, 4100, 3000, 4100]
Finance [Maria, Scott, Jen] [3000, 3300, 3900]
Marketing [Jeff, Kumar] [3000, 2000]
1

2 Answers 2

4

Use collect_list with groupBy clause

from pyspark.sql.functions import *

df.groupBy(col("department")).agg(collect_list(col("employee_name")).alias("employee_name"),collect_list(col("employee_name")).alias("salary"))
Sign up to request clarification or add additional context in comments.

Comments

2

Lets try with minimal typing;

df.groupby('department').agg(*[collect_list(c).alias(c) for c in df.drop('department').columns]).show()

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.