×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Reset a column multiindex levels

Given a pandas multiindex dataframe, we have to reset a column multiindex levels. By Pranit Sharma Last updated : September 30, 2023

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.

Multilevel indexing is a type of indexing that 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 the multilevel index followed by level 1, level 2, and so on.

Resetting a column multiindex levels

For this purpose, we will use DataFrame.columns.droplevel() method (this method returns Series/DataFrame with requested index / column level(s) removed) inside which we will pass the level number.

Let us understand with the help of an example,

Python program to reset a column multiindex levels

# Importing pandas package
import pandas as pd

# Creating multiindex DataFrame
# 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 Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Dropping column levels
df.columns = df.columns.droplevel(0)

# Display result
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Reset a column multiindex levels

Python Pandas Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.