Pandas: Split the specified dataframe into groups based on first column and set other column values into a list of values
13. Grouping by First Column and Aggregating into Lists
Write a Pandas program to split the following dataframe into groups based on first column and set other column values into a list of values.
Test Data:
X Y Z 0 10 10 22 1 10 15 20 2 10 11 18 3 20 20 20 4 30 21 13 5 30 12 10 6 10 14 0
Sample Solution:
Python Code :
Sample Output:
Original DataFrame: X Y Z 0 10 10 22 1 10 15 20 2 10 11 18 3 20 20 20 4 30 21 13 5 30 12 10 6 10 14 0 Y Z X 10 [10, 15, 11, 14] [22, 20, 18, 0] 20 [20] [20] 30 [21, 12] [13, 10]
For more Practice: Solve these Related Problems:
- Write a Pandas program to group the dataframe by the first column and then aggregate the remaining columns into lists.
- Write a Pandas program to split a dataframe by its first column and convert the values of other columns to lists per group.
- Write a Pandas program to group the dataset on the first column and then display each group’s values as a list.
- Write a Pandas program to group by the first column and then merge the remaining column values into a single list for each group.
Go to:
Previous: Write a Pandas program to split the following dataframe into groups, group by month and year based on order date and find the total purchase amount year wise, month wise.
Next: Write a Pandas program to split the following dataframe into groups based on all columns and calculate Groupby value counts on the dataframe.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.