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

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



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]
Updated on: 2021-09-30T12:13:18+05:30

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements