For data manipulation tasks, grouping rows into lists based on specific criteria is a common requirement. In Pandas, the groupby function provides a powerful tool for this purpose.
Suppose you have a DataFrame with two columns, 'a' and 'b':
a b A 1 A 2 B 5 B 5 B 4 C 6
The goal is to group rows based on the 'a' column and create lists of the 'b' column for each group.
To achieve this, you can leverage the groupby function:
df.groupby('a')['b'].apply(list)
The groupby function groups the DataFrame by the 'a' column. The apply function then iterates over each group and converts the 'b' column to a list using list.
The resulting output:
a A [1, 2] B [5, 5, 4] C [6] Name: b, dtype: object
This technique enables you to efficiently group rows based on a specific column and obtain lists of values for other columns within each group.
The above is the detailed content of How Can Pandas' `groupby` Function Efficiently Create Lists of Values from Grouped Rows?. For more information, please follow other related articles on the PHP Chinese website!