Quickest way to swap index with values

Here, we are going to find the quickest way to swap index with values.
Submitted by Pranit Sharma, on November 17, 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.

Swapping index with values

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.

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 code 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)


Example: Quickest way to swap index with values

Python Pandas Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.