The Wayback Machine - https://web.archive.org/web/20240712233622/https://www.geeksforgeeks.org/access-index-of-last-element-in-pandas-dataframe-in-python/
Open In App

Access Index of Last Element in pandas DataFrame in Python

Last Updated : 28 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to access an index of the last element in the pandas Dataframe. To achieve this, we can use Dataframe.iloc, Dataframe.iget, and Dataframe.index. let’s go through all of them one by one. 

 Dataframe.iloc –  Pandas Dataframe.iloc is used to retrieve data by specifying its index. In python negative index starts from the end so we can access the last element of the dataframe by specifying its index to -1.

Syntax: pandas.DataFrame.iloc[]

Parameters:

Index Position: Index position of rows in integer or list of integer.

Return type: Data frame or Series depending on parameters

Example 1: The following program is to access the index of the last element from the entire Dataframe. 

Python3




# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Rahul', 
                            'Krish', 'Rohit'],
                   'Course': ['BCA', 'MBA', 'MBA', 'BCA',
                              'BBA'],
                   'Address': ['Saharanpur', 'Mohali',
                               'Saharanpur', 'Mohali', 
                               'Noida']})
  
# Display original dataframe
print("Original dataframe")
print(df)
  
# Display last index value of dataframe
# iloc[-1] is return the last element of 
# all columns in DataFrame.
print("value of last index column")
print(df.iloc[-1])


Output:

Example 2:

 The following program is to access the index of the last element from a specific column. 

Python3




# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Name': ['Mukul', 'Rohan', 'Rahul',
                            'Krish', 'Rohit'],
                   'Course': ['BCA', 'MBA', 'MBA', 
                              'BCA', 'BBA'],
                   'Address': ['Saharanpur', 'Mohali', 
                               'Saharanpur', 'Mohali', 
                               'Noida']})
  
# Display original dataframe
print("Original dataframe")
print(df)
  
# Display last index value of Address dataframe
print("last index value of Address Column: ", df['Address'].iloc[-1])


Output:

Dataframe.iat() function – Pandas iat[] method is used to return data in a dataframe at the passed location. The passed location is in the format [position in the row, position in the column]. This method works similarly to Pandas iloc[] but iat[] is used to return only a single value and hence works faster than it.

Syntax: Dataframe.iat[row, column]

Parameters:  

  • position: Position of element in column
  • label: Position of element in row

Return type: Single element at passed position 

Example 3:

Under, this example we will be using the df.iat() function.

Python3




# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Name': ['sanjay', 'suresh',
                            'Rahul', 'Krish', 
                            'vihan'],
                   'Address': ['Haridwar', 'Mohali', 
                               'mohali', 'Mohali', 
                               'saharanpur']})
  
# Display original dataframe
print(" Original dataframe ")
print(df)
  
# Display last index value of 0 index column
print("last index value of 0 index column is ", df.iat[-1, 0])


Output:

Example 4:

In this example, we are using the df.index() function to access the last element of the given data frame in python language.

Python3




# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Name': ['Mukul', 'Rohan', 
                            'Rahul', 'Krish',
                            'Rohit'],
                   'Address': ['Saharanpur', 'Mohali', 
                               'Saharanpur', 'Mohali', 
                               'Noida']})
  
# Display original dataframe
print(" Original dataframe ")
print(df)
  
# Display last index value of dataframe
# iloc[-1] is return the last element of
# all columns in DataFrame.
print(" last index is ", df.index[-1])


Output:



Previous Article
Next Article

Similar Reads

How to select last row and access PySpark dataframe by index ?
In this article, we will discuss how to select the last row and access pyspark dataframe by index. Creating dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appNam
2 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to access the last element in a Pandas series?
Prerequisite: Pandas Pandas series is useful in handling various analytical operations independently or as being a part of pandas data frame. So it is important for us to know how various operations are performed in pandas series. The following article discusses various ways in which last element of a pandas series can be retrieved. Method 1: Naive
3 min read
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas
Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods. 1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame : Pandas head() method is used to return top n (5 by default) rows of a data frame or series Syntax: Dataframe.head(n). Parameters: (optional) n is integer value,
2 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
3 min read
How to Convert Dataframe column into an index in Python-Pandas?
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", "Pankaj
2 min read
Get last n records of a Pandas DataFrame
Let's discuss how to get last n records of a Pandas DAtaframe. There can be various methods to get the last n records of a Pandas DataFrame. Lets first make a dataframe:Example: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Go
2 min read
Remove last n rows of a Pandas DataFrame
Let's see the various methods to Remove last n rows of a Pandas Dataframe.First, let's make a dataframe: C/C++ Code # Import Required Libraries import pandas as pd # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Marks': [90, 84, -33, -87
3 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
three90RightbarBannerImg