Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Concatenate MultiIndex into Single Index using Pandas and NumPy



To concatenate multiindex into single index, at first, let us import the required Pandas and Numpy libraries with their respective aliases −

import pandas as pd
import numpy as np

Create Pandas series −

d = pd.Series([('Jacob', 'North'),('Ami', 'East'),('Ami', 'West'),('Scarlett', 'South'),('Jacob', 'West'),('Scarlett', 'North')])

Now, use the Numpy arrange() method −

dataFrame = pd.Series(np.arange(1, 7), index=d)

Let us now map and join −

dataMap = dataFrame.index.map('_'.join)

Example

Following is the code −

import pandas as pd
import numpy as np

# pandas series
d = pd.Series([('Jacob', 'North'),('Ami', 'East'),('Ami', 'West'),('Scarlett', 'South'),('Jacob', 'West'),('Scarlett', 'North')])

dataFrame = pd.Series(np.arange(1, 7), index=d)

# mapping and joining
dataMap = dataFrame.index.map('_'.join)

print"\nResult after mapping:\n",dataMap

Output

This will produce the following output −

Result after mapping:
Index([u'Jacob_North', u'Ami_East', u'Ami_West', u'Scarlett_South', u'Jacob_West', u'Scarlett_North'],dtype='object')
Updated on: 2021-09-15T08:06:10+05:30

506 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements