Python - How to group DataFrame rows into list in Pandas?

PythonServer Side ProgrammingProgramming

To group dataframe rows into list, use the apply() function. At first, let us import the require library −

import pandas as pd

Create DataFrame with 2 columns −

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

Grouping DataFrame into list with apply(list) −

dataFrame = dataFrame.groupby('Car')['Units'].apply(list)

Example

Following is the code −

import pandas as pd

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

print"DataFrame ...\n",dataFrame

# grouping dataframe into lists
dataFrame = dataFrame.groupby('Car')['Units'].apply(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     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

DataFrame ...
 Car
Audi      [110]
BMW       [100]
Bentley   [110]
Jaguar     [90]
Lexus     [150]
Mustang    [80]
Name: Units, dtype: object
raja
Published on 20-Sep-2021 09:19:45
Advertisements