How to apply the aggregation list on every group of pandas DataFrame?

PythonServer Side ProgrammingProgramming

To apply the aggregation list, use the agg() method. At first, import the required library −

import pandas as pd

Create a DataFrame with two columns −

dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, 110, 80, 110, 90]
   }
)

Specifying list as argument using agg() −

dataFrame = dataFrame.groupby('Car').agg(list)

Example

Following is the complete code −

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'],"Units": [100, 150, 110, 80, 110, 90]
   }
)

print("DataFrame ...\n",dataFrame)

# specifying list as argument using agg()
dataFrame = dataFrame.groupby('Car').agg(list)

# displaying dataframe lists
print("\nDataFrame ...\n",dataFrame)

Output

This will produce the following output −

DataFrame ...
       Car   Units
0      BMW     100
1    Lexus     150
2    Lexus     110
3  Mustang      80
4  Bentley     110
5  Mustang      90

DataFrame ...
            Units
Car
BMW         [100]
Bentley     [110]
Lexus   [150,110]
Mustang   [80,90]
raja
Published on 30-Sep-2021 12:13:18
Advertisements