Python:Pandas first()
The first() method in pandas returns the first non-null value from each group created by a groupby() operation. It is commonly used to extract representative or initial entries for grouped data, such as the first transaction, first record, or earliest occurrence.
Syntax
DataFrameGroupBy.first(numeric_only=False, min_count=-1, skipna=True)
Parameters:
numeric_only(bool, defaultFalse): Includes only float, int, and boolean columns in the operation.min_count(int, default-1): Minimum number of valid values required to perform the operation. If fewer values are available, returnsNaN.skipna(bool, defaultTrue): ExcludesNA/nullvalues. If all entries areNA, the result isNA.
Return value:
Returns a Series or DataFrame containing the first non-null value from each group.
Example 1
In this example, the method retrieves the first entry of each department from the DataFrame:
import pandas as pddata = {'Department': ['HR', 'Finance', 'HR', 'IT', 'Finance', 'IT'],'Employee': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank'],'Salary': [50000, 60000, 52000, 58000, 61000, 59000]}df = pd.DataFrame(data)result = df.groupby('Department').first()print(result)
The output of this code is:
Employee SalaryDepartmentFinance Bob 60000HR Alice 50000IT David 58000
Example 2
In this example, the method extracts the first available record for each city group while skipping missing values:
import pandas as pdimport numpy as npdata = {'City': ['Delhi', 'Delhi', 'Mumbai', 'Mumbai', 'Chennai', 'Chennai'],'Temperature': [32, np.nan, 30, 29, np.nan, 27],'Humidity': [80, 82, 75, 78, 70, 72]}df = pd.DataFrame(data)result = df.groupby('City').first()print(result)
The output of this code is:
Temperature HumidityCityChennai 27.0 70Delhi 32.0 80Mumbai 30.0 75
Codebyte Example
In this example, the method finds the first purchase record for each customer, showing how it can be applied to analyze grouped transaction data:
Frequently Asked Questions
1. What does groupby().first() do?
groupby().first() returns the first non-null record from each group in a grouped pandas object.
2. How do you get the first in a pandas group?
By applying the first() method after using groupby(), such as df.groupby('Column').first().
3. How to print the first 10 rows of a pandas DataFrame?
Use the head(10) method, which displays the first 10 rows of the DataFrame.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pandas on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours