Home > Backend Development > Python Tutorial > How to Retrieve the Initial Row of Each Group in a Pandas DataFrame?

How to Retrieve the Initial Row of Each Group in a Pandas DataFrame?

DDD
Release: 2024-11-10 22:52:02
Original
182 people have browsed it

How to Retrieve the Initial Row of Each Group in a Pandas DataFrame?

Pandas Dataframe: Retrieve the Initial Row of Each Group

Question

Consider a dataset represented as a pandas DataFrame with columns 'id' and 'value'. The objective is to identify the first row for each distinct combination of 'id' and 'value'.

Solution

To obtain the first row of each group, utilize df.groupby('id').first(). This method retrieves the first non-null element for each 'id' group.

If you require the 'id' column in the resulting DataFrame, you can employ df.groupby('id').first().reset_index().

To acquire the first 'n' records within each group, utilize df.groupby('id').head(n).reset_index(drop=True).

The above is the detailed content of How to Retrieve the Initial Row of Each Group in a Pandas DataFrame?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template