Home > Backend Development > Python Tutorial > How Can Pandas' `groupby` Function Efficiently Create Lists of Values from Grouped Rows?

How Can Pandas' `groupby` Function Efficiently Create Lists of Values from Grouped Rows?

Susan Sarandon
Release: 2024-12-28 05:46:10
Original
161 people have browsed it

How Can Pandas' `groupby` Function Efficiently Create Lists of Values from Grouped Rows?

Efficiently Grouping Rows into Lists in Pandas via Groupby

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
Copy after login

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)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template