Quickest way to swap index with values

Here, we are going to find the quickest way to swap index with values. By Pranit Sharma Last updated : October 05, 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.

Problem statement

Suppose we are given a Series containing the index of some strings and values of some strings, we need to find the quickest way to swap these index values and their corresponding values.

Swapping index with values

For this purpose, we will use Series.iteritems() method. This method will separate the index and the corresponding values in key-value pairs, so using this method inside a for loop will continuously return the key and its value one by one.

By accessing each key and value, we can directly swap them or convert them into a dictionary in the opposite order i.e., we will make the keys as values and values as keys.

Let us understand with the help of an example,

Python program to swap index with values

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a Series
s = pd.Series(['one','two','three','four','five','six','seven','eight','nine'],list('123456789'))

# Display Series
print('Original Series:\n',s,'\n')

# Swapping the index and values
res = pd.Series(dict((v,k) for k,v in s.iteritems()))

# Display new series
print("New Series:\n",res)

Output

The output of the above program is:

Example: Quickest way to swap index with values

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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