Python Pandas - Getting values from a specific level in Multiindex

PythonPandasServer Side ProgrammingProgramming

To get values from a specific level in Multiindex, use the multiIndex.get_level_values() method in Pandas.

At first, import the required libraries −

import pandas as pd

Create a multi-index. The names parameter sets the names for the levels in the index

multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]],
   names=['a', 'b', 'c', 'd'])

Get value from specific value. Get 0th level value −

print("\nGet level value (0th level)...\n",multiIndex.get_level_values(0))

Get 1st level value −

print("\nGet level value (1st level)...\n",multiIndex.get_level_values(1))

Example

Following is the code −

import pandas as pd

# Create a multi-index
# The names parameter sets the names for the levels in the index
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]],
names=['a', 'b', 'c', 'd'])

print("Multi-index...\n",multiIndex)

# get 0th level value
print("\nGet level value (0th level)...\n",multiIndex.get_level_values(0))

# get 1st level value
print("\nGet level value (1st level)...\n",multiIndex.get_level_values(1))

# dropping a level from the multiindex
print("\nDropping a level...\n",multiIndex.droplevel())

Output

This will produce the following output −

Multi-index...
MultiIndex([( 5, 15, 25, 35),
(10, 20, 30, 40)],
names=['a', 'b', 'c', 'd'])

Get level value (0th level)...
Int64Index([5, 10], dtype='int64', name='a')

Get level value (1st level)...
Int64Index([15, 20], dtype='int64', name='b')

Dropping a level...
MultiIndex([(15, 25, 35),
(20, 30, 40)],
names=['b', 'c', 'd'])
raja
Published on 14-Oct-2021 08:43:30

Advertisements