• Post author:
  • Post category:Pandas
  • Post last modified:May 7, 2024
  • Reading time:18 mins read
You are currently viewing Pandas Get Last Row from DataFrame?

To get the last row from a Pandas DataFrame, you can use either the .iloc indexer with a negative index or the .tail() method. To get the last row of a Pandas DataFrame, you can utilize the iloc[-1] property or the tail(1) method. iloc[] allows the selection of rows and columns by position/index. If the specified index is out of range, it raises an IndexError. In this article, I will explain the get the last row of Pandas DataFrame.

Advertisements

pandas loc[] is another property that is used to operate on the column and row labels. For a better understanding of these two learn the differences and similarities between pandas loc[] vs iloc[].

Key Points –

  • The iloc[-1] method retrieves the last row of a DataFrame using negative indexing.
  • Utilizing the tail(1) function is another approach to obtaining the last row of a DataFrame.
  • Both iloc[-1] and tail(1) methods return a Series containing the values of the last row.
  • Retrieving the last row is a common operation in data analysis for summarizing or examining the latest data point in a dataset.

Quick Example of Get the Last Row

If you are in a hurry, below are some quick examples of getting the last row of Pandas DataFrame.


# Quick examples of get the last row of dataframe

# Example 1: Get last row 
# Using row position
print(df.iloc[-1])

# Example 2: Get the last row 
# Use tail()
print(df.tail(1))

# Example 3: Get last row 
# Using range index
print(df.iloc[-1:])

# Example 4: Get last row value 
# Using particular column
print(df['Fee'].iloc[-1])

# Example 5: Get last row value 
# Using index range
print(df['Discount'].iloc[:-1])

# Example 6: Get last row 
# Using loc() function
print(df.loc[df.index[-1]])

# Example 7: Get last row 
# Using values[]
print(df.values[-1:])

# Example 8: Get last row of particular column
print(df['Fee'].values[-1:])

# Example 9: Get the last row of DataFrame as a list
print(df.iloc[-1].tolist())

Let’s create a DataFrame using data from the Python dictionary using data from the Python dictionary then use the above examples to get the first row of DataFrame.


# Import pandas library
# Create pandas DataFrame
import pandas as pd
technologies = {
    'Courses':["Spark","PySpark","Hadoop","Python","pandas"],
    'Fee' :[20000,25000,26000,22000,24000],
    'Duration':['30days','40days','35days','40days','60days'],
    'Discount':[1000,2300,1200,2500,2000]
              }
index_labels=['r1','r2','r3','r4','r5']
df = pd.DataFrame(technologies, columns = ['Courses', 'Fee', 'Duration', 'Discount'], index = index_labels)
print("Create a DataFrame:\n", df)

Yields below output.

pandas get last row

Using iloc[] to Get the Last Row

To get the last row of a Pandas DataFrame using iloc[], you simply need to use -1 as the index within the iloc[] method. iloc[-1] property returns the last row of DataFrame in the form of Pandas Series.

In the below example, to get the last row of a Pandas DataFrame using .iloc[] with negative indexing. Here, df.iloc[-1] accesses the last row of the DataFrame using negative indexing. This is a concise and commonly used method to retrieve the last row.

Related Article: Get the first row of Pandas DataFrame.


# Get the last row using row position
df2 = df.iloc[-1]
print("Get the last row from the DataFrame:\n", df2)

Yields below output.

pandas get last row

We can also get the last row of Pandas DataFrame by providing an index range i.e.[-1:] to iloc[] attribute. This syntax will be returned the last in the form of DataFrame. For example,


# Get last row using range index
df2 = df.iloc[-1:]
print("Get the last row from the DataFrame:\n", df2)

# Output:
# Get the last row from the DataFrame:
#    Courses    Fee Duration  Discount
# r5  pandas  24000   60days      2000

Get the Last Row for a Particular Column

If you want to get the last row based on a particular column, we can pass the specified column into DataFrame and then call the iloc[] attribute, it will return the last row based on the specified column.

Replace Fee with the actual name of the column for which you want to get the last value. This will print the last value in the specified column of your DataFrame.


# Get last row value using particular column
df2 = df['Fee'].iloc[-1]
print("Get the last row value of specified column:\n", df2)

# Output:
# Get the last row value of specified column:
# 24000

Alternatively, you can retrieve the last row based on a particular column using the index range of the iloc[] attribute.


# Get last row value using index range
df2 = df['Discount'].iloc[:-1]
print("Get the last row value:\n", df2)

# Output:
# Get the last row value:
# r5    2000
# Name: Discount, dtype: int64

Get the Last Row using loc()

We can also get the last row of DataFrame using the loc[] attribute for that, we have to pass the last row index with the help of the index[]. It will return the last row as a Series object.

When using loc[] to get the last row of a Pandas DataFrame, you need to use the index label of the last row. If your DataFrame has a default integer-based index. This assumes that the index labels are integers. If your DataFrame has a custom index, you would use the actual label instead.


# Get last row using loc() function
df2 = df.loc[df.index[-1]]
print("Get the last row from the DataFrame:\n", df2)

# Output:
# Get the last row from the DataFrame:
# Courses     pandas
# Fee          24000
# Duration    60days
# Discount      2000
# Name: r5, dtype: object

Get the Last Row of Pandas using values[] 

Pandas DataFrame.values attribute is used to return a Numpy representation of the given DataFrame. Use this attribute to get the last row of DataFrame in the form of a NumPy array.


# Get last row using values[] 
df2 = df.values[-1:]
print("Get the last row from the DataFrame:\n", df2)


# Output:
# Get the last row from the DataFrame:
# [['pandas' 24000 '60days' 2000]]


# Get last row of particular column
df2 = df['Fee'].values[-1:]
print("Get the last row from the DataFrame:\n", df2)

# Output:
# Get the last row from the DataFrame:
# [24000]

Get the Last Row of DataFrame using the tail()

The pandas.DataFrame.tail() method returns the last n rows of DataFrame. We can use this tail() function to get only the last row of the DataFrame, for that, we pass '1' as an argument to this function. It will return the last row of DataFrame.


# Get the last row use head()
df2 = df.tail(1)
print("Get the last row from the DataFrame:\n", df2)

# Output:
# Get the last row from the DataFrame:
#     Courses    Fee Duration  Discount
# r5  pandas  24000   60days      2000

Get the Last Row of Pandas as a List

As we know from the above, we have got the last row of DataFrame using the df.iloc[-1]. It has given the result as a series object and then uses the series.tolist() function, we can get the last row of the DataFrame in the form of a list. For example,


# Get the last row of DataFrame as a list
df2 = df.iloc[-1].tolist()
print("Get the last row from the DataFrame:\n", df2)

# Output:
# Get the last row from the DataFrame:
# ['pandas', 24000, '60days', 2000]

Frequently Asked Questions on Pandas Get Last Row from DataFrame

How can I get the last row from a Pandas DataFrame?

To get the last row from a Pandas DataFrame, you can use either the .iloc indexer with a negative index or the .tail() method.

Can I use .tail() to get the last row?

You can use the .tail() method to get the last n rows of a Pandas DataFrame, and if you set n to 1, it will give you only the last row. The .tail(1) method returns a DataFrame containing the last row of the original DataFrame. If you only need the last row and want the result as a Series instead of a DataFrame.

What is the difference between using .iloc[-1] and .tail(1)?

While both methods will give you the last row, there is a subtle difference. .iloc[-1] returns a Series object, while .tail(1) returns a DataFrame with one row. If you want a Series, use .iloc[-1]; if you prefer a DataFrame with a single row, use .tail(1).

How can I get the last row if the DataFrame is empty?

If the DataFrame is empty, attempting to access the last row using .iloc[-1] will result in an IndexError. It’s advisable to check for an empty DataFrame before attempting to retrieve the last row.

Are there any other methods to get the last row?

Another approach is to use the iloc property with the shape attribute. This method is less concise but might be useful in certain situations.

Can I use .iloc with a negative index for other rows as well?

You can use .iloc with a negative index to access rows from the end of a Pandas DataFrame. Negative indexing in Python allows you to access elements from the end of a sequence.

Conclusion

In this article, I have explained the usage of DataFrame.iloc[] and using this how we can get the last row of DataFrame in different ways. As well as I explained how to get the last row using tail() and other functions.

Happy Learning !!

References