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

How to Extract the First Row of Each Group in a Pandas DataFrame?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 06:34:02920browse

How to Extract the First Row of Each Group in a Pandas DataFrame?

Pandas DataFrame: Get First Row of Each Group

In this context, you have a pandas DataFrame with grouped data and want to extract the first row from each group. This can be achieved through various methods.

One straightforward approach is to utilize the first() function, which retrieves the first non-null value from each column:

df.groupby('id').first()

This method excludes the index column from the output. To include the id column as a column, use reset_index():

df.groupby('id').first().reset_index()

Alternatively, you can use head(n) to obtain the first n rows from each group:

df.groupby('id').head(2).reset_index(drop=True)

In this example, the drop=True parameter removes the reset index column from the output.

Another approach involves setting the as_index parameter in groupby():

df.groupby('id', as_index=False).nth(0)

This method includes id as a column by default.

Remember to adjust these methods based on your specific requirements for column inclusion and the number of rows to be retrieved.

The above is the detailed content of How to Extract the First Row of Each Group in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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