Python Pandas and Numpy - Concatenate multiindex into single index

PythonServer Side ProgrammingProgramming

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')
raja
Published on 15-Sep-2021 08:06:10
Advertisements