Home »
Python »
Python Programs
How to select rows in pandas MultiIndex DataFrame?
Given a pandas MultiIndex DataFrame, we have to select rows.
By Pranit Sharma Last updated : September 21, 2023
Columns are the different fields which contains their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. In this article, we are going to learn how to drop a level from a multi-level column index.
Multilevel Indexing
Multilevel indexing is a type of indexing which include different levels of indexes or simply multiple indexes. The DataFrame is classified under multiple indexes and the topmost index layer is presented as level 0 of multilevel index followed by level 1, level 2 and so on.
Problem statement
Given a pandas MultiIndex DataFrame, we have to select rows.
Selecting rows in pandas MultiIndex DataFrame
Step 1: Create a multilevel index DataFrame
To understand how to select a row from a multiindex DataFrame, we first need to create a multilevel index DataFrame.
Note
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
# Importing pandas package
import pandas as pd
# Creating multilevel index
index = pd.MultiIndex.from_tuples([('Vitamin A','Sources'),
('Vitamin C', 'Sources'),
('Vitamin D','Sources')])
# Creating a multilevel index DataFrame with
# columns = multilevel indexes
df = pd.DataFrame([['Papaya','Orange','Oily Fish'],
['Watermelon','Blackcurrent','Red meat'],
['Mango','Kale','egg yolks']], columns=index)
# Display multilevel DataFrame
print("Multilevel DataFrame:\n",df)
The output of the above program is:
Step 2: Select rows in pandas MultiIndex DataFrame
Now we will select a row from this Multiindex DataFrame. We will use DataFrame.loc[] property for the purpose of selecting a row.
# Selecting row from this
# multiindex DataFrame
result = df.loc[0,['Vitamin A']]
print("Selected Row:\n",result)
The output of the above program is:
Python Pandas Programs »