How to List values for each Pandas group?

How to List values for each Pandas group?

If you want to list values for each group in a pandas DataFrame, you can use the groupby method along with the apply(list) function. This will provide a list of values for each unique group.

Here's an example to illustrate this:

Consider the following DataFrame:

import pandas as pd data = { 'Category': ['A', 'B', 'A', 'C', 'B', 'C', 'A'], 'Value': [10, 20, 10, 30, 20, 30, 10] } df = pd.DataFrame(data) print(df) 

This will output:

 Category Value 0 A 10 1 B 20 2 A 10 3 C 30 4 B 20 5 C 30 6 A 10 

To list values for each group in the 'Category' column:

grouped = df.groupby('Category')['Value'].apply(list).reset_index() print(grouped) 

This will output:

 Category Value 0 A [10, 10, 10] 1 B [20, 20] 2 C [30, 30] 

Now, the 'Value' column of the grouped DataFrame contains lists of values for each unique group in the 'Category' column.


More Tags

react-boilerplate android-holo-everywhere internet-explorer-11 automationanywhere polish lambda char resttemplate email-parsing jquery-cookie

More Programming Guides

Other Guides

More Programming Examples