How to get the index of ith item in pandas.Series or pandas.DataFrame?

Learn, how to get the index of ith item in pandas.Series or pandas.DataFrame? By Pranit Sharma Last updated : October 06, 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.

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.

Getting the index of ith item in pandas.Series or pandas.DataFrame

When we analyze a series, each value can be considered as a separate row of a single column. We are given the dataframe with multiple columns and each column contains a large number of values. If we talk about a single column, it will be considered as a series, now suppose we need to access the 4th index name; we can use the head() method where we can pass 4 as a parameter and after that, we can access the index.

Rather than using this head() method, we will directly use series.index.values[] method.

Let us understand with the help of an example,

Python program to get the index of ith item in pandas.Series or pandas.DataFrame

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'a':['Raman','Bahar','Saumya','Vivek','Prashant'],
    'b':[20,21,22,21,20]
}

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

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

# Create a series from df column
s = pd.Series(df['a'])

# Accessing index value of 4th value
res = s.index.values[4]

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

Output

The output of the above program is:

Example: How to get the index of ith item in pandas.Series or pandas.DataFrame?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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