Q:

Pandas: Drop a level from a multi-level column index

belongs to collection: Python Pandas Programs

0

Columns are the different fields that contain 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 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.

To understand how to drop a level from a multilevel column index, we first need t to create a multilevel index DataFrame.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Let us understand with the help of an example:

Here, we are creating column wise multilevel index one below another, for this purpose, we have MultiIndex.from_tuples() method.

# 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)

Output:

Example 1: Drop a level from a multi-level column index

Now we will drop a level of columns from this Multiindex DataFrame.

# Dropping a level of column where column 
# is sources i.e., level=1
df.columns = df.columns.droplevel(1)

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

Output:

Example 1: Drop a level from a multi-level column index

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Get column index from column name in Python pandas... >>
<< Pandas read in table without headers...