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
Release: 2024-11-10 06:34:02
Original
907 people have browsed it

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

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

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

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

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

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!

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