Group rows into a list in Pandas using lambda
We can use groupby() method on column 1 and agg() method to apply aggregation, consisting of the lambda function, on every group of pandas DataFrame.
Python3
# importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({ 'column1' : [ 'A' , 'B' , 'C' , 'A' , 'C' , 'C' , 'B' , 'D' , 'D' , 'A' ], 'column2' : [ 5 , 10 , 15 , 20 , 25 , 30 , 35 , 40 , 45 , 50 ]}) # Use groupby method and agg method # with lambda function on the dataframe df = df.groupby( 'column1' ).agg({ 'column2' : lambda x: list (x)}) # Print the dataframe again df |
Output:
How to group dataframe rows into list in Pandas Groupby?
Suppose you have a Pandas DataFrame consisting of 2 columns and we want to group these columns. In this article, we will discuss the same.