Python Pandas - Drop the value when all levels are NaN in a Multi-index


To drop the value when all levels are NaN in a Multi-index, use the multiIndex.dropna() method. Set the parameter how with value all.

At first, import the required libraries -

import pandas as pd
import numpy as np

Create a multi-index with all NaN values. The names parameter sets the names for the levels in the index −

multiIndex = pd.MultiIndex.from_arrays([[np.nan, np.nan], [np.nan, np.nan]],
names=['a', 'b'])

Drop the value when all levels iareNaN in a Multi-index. With all NaN values, the dropna() will drop all the values, if the "how" parameter of the dropna() is set "all" −

print("\nDropping the values when all levels are NaN...\n",multiIndex.dropna(how='all'))

Example

Following is the code −

import pandas as pd
import numpy as np

# Create a multi-index with all NaN values
# The names parameter sets the names for the levels in the index
multiIndex = pd.MultiIndex.from_arrays([[np.nan, np.nan], [np.nan, np.nan]],
names=['a', 'b'])

# display the multi-index
print("Multi-index...\n", multiIndex)

# Drop the value when all levels iareNaN in a Multi-index
# With all NaN values, the dropna() will drop all the values, if the
# "how" parameter of the dropna() is set "all"
print("\nDropping the values when all levels are NaN...\n",multiIndex.dropna(how='all'))

Output

This will produce the following output −

Multi-index...
MultiIndex([(nan, nan),(nan, nan)],names=['a', 'b'])

Dropping the values when all levels are NaN...
MultiIndex([], names=['a', 'b'])

Updated on: 13-Oct-2021

794 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements