How to convert pandas series to tuple of index and value?

Given a pandas series, we have to convert it into tuple of index and value.
Submitted by Pranit Sharma, on October 04, 2022

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.

Index in pandas is just the number of rows defined in a Series or DataFrame. The index always starts from 0 to n-1 where n is the number of rows. The index is used in indexing which is a method of traversing or selecting particular rows and columns or selecting all the rows and columns.

Problem statement

Suppose, we are given a DataFrame, we need to find an efficient way to convert pandas series to a tuple.

Converting pandas series to tuple of index and value

For this purpose, we will use the zip() method inside which we will pass the series and the index of the series so that the index and values can be together paired inside a tuple.

Let us understand with the help of an example,

Python program to convert pandas series to tuple of index and value

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[1,2,3,4,5],
    'B':[6,7,8,9,10]
}

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

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

# Creating a series
ser = pd.Series(df['A'])

# Binding index and values together
res = list(zip(ser,ser.index))

# creating tuple
res = tuple(res)

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

Output

The output of the above program is:

Example: Convert pandas series to tuple of index and value

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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