Python:Pandas .last()
Anonymous contributor
Published Oct 31, 2025
The .last() method is an aggregation function used on a GroupBy object in Pandas. It returns the last non-null value in each section of the grouped data. This method is particularly useful for time-series data or sequentially ordered data where the final observation within a specific period or category is the most relevant.
Syntax
The method is called directly on a GroupBy object.
grouped_data.last(numeric_only=False, min_count=-1)
Parameters:
numeric_only(bool): IfTrue, only attempts to aggregate numeric columns.min_count(int): The required number of valid (non-NA) values to include the result. If fewer thanmin_countnon-NA values are present, the result will beNaN.
Return value:
Returns a Series or DataFrame containing the last non-null value for each group.
Example
The following example demonstrates how to use .last() to find the final status of a task for each project:
import pandas as pd# Create a DataFrame representing chronological task status updatesdata = {'project_id': ['A', 'B', 'A', 'C', 'B', 'C', 'A'],'status_date': pd.to_datetime(['2025-01-01', '2025-01-05', '2025-01-10', '2025-01-15', '2025-01-20', '2025-01-25', '2025-01-30']),'task_status': ['Start', 'Pending', 'In Progress', 'Start', 'Completed', 'In Progress', 'Completed']}df = pd.DataFrame(data).set_index('status_date').sort_index()print("Original Data:\n", df)# Group by project_id and find the last status (chronologically) for each projectlast_status = df.groupby('project_id').last()print("\nLast Status by Project:\n", last_status)
The above code returns the following output:
Original Data:project_id task_statusstatus_date2025-01-01 A Start2025-01-05 B Pending2025-01-10 A In Progress2025-01-15 C Start2025-01-20 B Completed2025-01-25 C In Progress2025-01-30 A CompletedLast Status by Project:task_statusproject_idA CompletedB CompletedC In Progress
Codebyte Example
This codebyte example groups data by category and returns the last recorded value from each group:
All contributors
- Anonymous contributor
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