How to access the last element in a pandas series?

Given a pandas series, we have to access the last element in a pandas series. By Pranit Sharma Last updated : October 01, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

A series in pandas contains a single list that can store heterogeneous types of data, because of this, a series is also considered a 1-dimensional data structure.

When we analyze a series, each value can be considered as a separate row of a single column, both series and DataFrame can be created either with the list or with the help of a dictionary, in the case of series, there will be only one key in the dictionary but there may be multiple keys in case of DataFrame.

Accessing the last element in a pandas series

To access the last element of a series, we will use the iloc[] property using integer-based indexing. Use -1 as the index inside iloc[] property, it will return the last element of the series.

Let us understand with the help of an example,

Python program to access the last element in a pandas series

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'Brand':['Tata','Godrej','Amul'],
    'Product':['Tea','Soap','Milk'],
    'Price':[100,60,58]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Creating a series out of a column
ser = pd.Series(df['Brand'])

# Selecting last element of series
res = ser.iloc[-1]

# Display result
print("Result:\n",res)

Output:

Example: Access the last element in a pandas series

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.