Reset a column multiindex levels

Given a pandas multiindex dataframe, we have to reset a column multiindex levels.
Submitted by Pranit Sharma, on September 20, 2022

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.

Resetting a column multiindex levels

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.

We are going to drop a multiindex column, for this purpose, we will use DataFrame.columns.droplevel() method inside which we will pass the level number.

Let us understand with the help of an example,

Python code 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:

Example: Reset a column multiindex levels

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.