
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Compute last of group values in a Pandas DataFrame
To compute last of group values, use the groupby.last() method. At first, import the required library with an alias −
import pandas as pd;
Create a DataFrame with 3 columns −
dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'BMW', 'Tesla', 'Lexus', 'Tesla'],"Place": ['Delhi','Bangalore','Pune','Punjab','Chandigarh','Mumbai'],"Units": [100, 150, 50, 80, 110, 90] } )
Now, group DataFrame by a column −
groupDF = dataFrame.groupby("Car")
Compute last of group values and resetting index −
res = groupDF.last() res = res.reset_index()
Example
Following is the complete code. The last occurrence of repeated values are displayed i.e. last of group values −
import pandas as pd; dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'BMW', 'Tesla', 'Lexus', 'Tesla'],"Place": ['Delhi','Bangalore','Pune','Punjab','Chandigarh','Mumbai'],"Units": [100, 150, 50, 80, 110, 90] } ) print"DataFrame ...\n",dataFrame # grouping DataFrame by column Car groupDF = dataFrame.groupby("Car") res = groupDF.last() res = res.reset_index() print"\nLast of group values = \n",res
Output
This will produce the following output −
DataFrame ... Car Place Units 0 BMW Delhi 100 1 Lexus Bangalore 150 2 BMW Pune 50 3 Tesla Punjab 80 4 Lexus Chandigarh 110 5 Tesla Mumbai 90 Last of group values = Car Place Units 0 BMW Pune 50 1 Lexus Chandigarh 110 2 Tesla Mumbai 90
- Related Articles
- Python - Compute first of group values in a Pandas DataFrame
- Python – Group and calculate the sum of column values of a Pandas DataFrame
- Python - Replace values of a DataFrame with the value of another DataFrame in Pandas
- Python - How to Group Pandas DataFrame by Month?
- Python - How to Group Pandas DataFrame by Days?
- Python – Sort grouped Pandas dataframe by group size?
- Python - How to Group Pandas DataFrame by Year?
- Python - How to Group Pandas DataFrame by Minutes?
- Python - Remove duplicate values from a Pandas DataFrame
- Python - Calculate the mean of column values of a Pandas DataFrame
- Python - Calculate the median of column values of a Pandas DataFrame
- Python - Calculate the count of column values of a Pandas DataFrame
- Python - Calculate the maximum of column values of a Pandas DataFrame
- Python - Calculate the minimum of column values of a Pandas DataFrame
- Python - How to group DataFrame rows into list in Pandas?

Advertisements