Access Index of Last Element in pandas DataFrame in Python


To access the index of the last element in the pandas dataframe we can use the index attribute or the tail() method. Pandas is a Python library used for data manipulation and analysis. Data frame is a data structure provided by pandas which is used to work with large datasets effectively. In this article we will understand how we can access the index of the last element in pandas data frame.

What is a Data Frame?

Data frame is a two-dimensional, tabular data structure which has rows and columns just like a matrix or spreadsheet or a SQL table. Any type of data like a CSV file, dictionary, or list of lists can be easily converted to a Data frame. Columns of the dataframe can have different data types like integer, float or strings etc. Each row of the data frame has a unique index which by default starts from 0. We can also specify a custom index to the dataframe row using set_index() method.

Accessing an Element in a Data Frame?

To access the last element index of a pandas data frame we need to first understand how an element of a data frame is accessed. To access any element of a dataframe we use the loc[] and iloc[] methods. For example let's consider a data frame,

    Subject   Marks    Grade
0   Maths      70        B
1   Science    85        A
2   Computer   90        A
3   English    45        C

The above data frame has three columns namely Subject, marks and Grade and four rows with index 0,1,2,3. The loc[] method takes row label and column label to access any element of the data frame. In the above example if we want to access the third row and the first column value of the data frame we can do that using loc[] method by −

Syntax

loc[row_label,column_label]

The loc[] method is used to access the element of a dataframe. The parameters row_label and column_label need to be passed to the loc method for accessing the specific element of the dataframe.

iloc[row_index,column_index]

The iloc[] method is used to access the element of a dataframe. The parameters row_index and column_index need to be passed to the loc method for accessing the specific element of the dataframe.

Example 1

Pandas will convert the dictionary into a dataframe using the pd.dataframe() method. Once the data frame is available in df variable we can access the value of the dataframe with row_label as 2 and column_label as ‘Subject’.

# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Subject': ['Maths', 'Science', 'Computer', 'English'],
   'Marks': ['70', '85', '90', '45'],
   'Grade': ['B', 'A','A', 'C']})
  
# Display original dataframe
print("Original dataframe")
print(df)
  

print(df.loc[2,'Subject'])

Output

Original dataframe
    Subject  Marks  Grade
0   Maths     70     B
1   Science   85     A
2   Computer  90     A
3   English   45     C
Computer

Example 2

In the similar way iloc[] method takes row and column index as argument to access any element of the data frame. If we want to access the fourth row and second column value then we can do that using iloc[] method as −

# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Subject': ['Maths', 'Science', 'Computer', 'English'],
   'Marks': ['70', '85', '90', '45'],
   'Grade': ['B', 'A', 'A', 'C']})
  
# Display original dataframe
print("Original dataframe")
print(df)
  

print(df.iloc[3,1])

Output

Original dataframe
    Subject Marks Grade
0   Maths    70     B
1   Science    85     A
2  Computer    90     A
3   English    45     C
45

Using Index Attribute

The index specifies the row index of the data frame. By default the index of the dataframe row starts from 0. To access the last row index we can start with -1.

Syntax

df.index[row_index]

The index attribute is used to access the index of the row in the data frame. To access the index of the last row we can start from negative values i.e -1.

For Example we will create the data frame as follows :

   Subject   Marks   Grade
0   Maths     70       B
1  Science    85       A
2  Computer   90       A
3  English    45       C

Example

# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Subject': ['Maths', 'Science', 'Computer', 'English'],
   'Marks': ['70', '85', '90', '45'],
   'Grade': ['B', 'A', 'A', 'C']})
  
# Display original dataframe
print("Original dataframe")
print(df)
  
# Display last index value of dataframe
# index[-1] is return the last row index of 
# all rows in DataFrame.
print("value of last row index")
print(df.index[-1])

Output

Original dataframe
    Subject  Marks  Grade
0   Maths     70     B
1   Science   85     A
2   Computer  90     A
3   English   45     C
value of last row index
3

Using tail() Method

The tail(n) method returns the value of the last nth row of the pandas data frame. If we want to get only the index of the last row we can use the index attribute with the tail method to get the index of the last row. The parameter n passed to the tail method returns the last n rows of the pandas data frame to get only the last row we can pass n=1.

Syntax

df.tail(nth_row_index)

The tail() method returns the value of the nth row from the end. The row_index starting from end is passed as argument to tail function.The index of the last row will start from 1.

df.tail(nth_row_index).index[column_index]

The tail() method returns the entire row value at the nth index from end. To access the specific index of the element at nth row we need to pass the column_index value to it.

Example

In this example we will convert the python dictionary data to a dataframe using the pd.Dataframe() method. We will use the index() and tail() method to get the index value of the last element or row in the dataframe,

# import pandas
import pandas as pd
  
# create dataframe
df = pd.DataFrame({'Subject': ['Maths', 'Science', 'Computer', 'English'],
   'Marks': ['70', '85', '90', '45'],
   'Grade': ['B', 'A', 'A', 'C']})
  
# Display original dataframe
print("Original dataframe")
print(df)
  
# Display last index value of dataframe
# index[-1] is return the last row index of 
# all rows in DataFrame.
print("value of last row")
print(df.tail(1))
print("value of last row index")
print(df.tail(1).index[0])

Output

Original dataframe
     Subject  Marks Grade
0    Maths     70     B
1    Science   85     A
2    Computer  90     A
3    English   45     C

value of last row
Subject Marks Grade
3  English    45     C
value of last row index
3

Conclusion

In this article we understood how to access any element in python pandas dataframe and how to access the index of the last element in pandas data frame using index attribute and tail method. The index attribute returns the index of the last row when negative index -1 is passed to it. The tail attribute returns the row value of the nth row from the end when row index starting from 1 for the last row is passed to it. To access the specific element index we can use tail and index attributes together.

Updated on: 13-Apr-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements