Python Pandas - Drop the value when any level is NaN in a Multi-index


To drop the value when any level is NaN in a Multi-index, use the multiIndex.dropna() method. Set the parameter how with value any.

At first, import the required libraries -

import pandas as pd
import numpy as np

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

multiIndex = pd.MultiIndex.from_arrays([[5, 10], [np.nan, 20], [25, np.nan], [35, 40]],names=['a', 'b', 'c', 'd'])

Drop the value when any level is NaN in a Multi-index. Even with a single NaN value, the dropna() will drop all the values. The "how" parameter of the dropna() is used with the value "any" for this −

print("\nDropping the value when any level is NaN...\n",multiIndex.dropna(how='any'))

Example

Following is the code −

import pandas as pd
import numpy as np

# Create a multi-index with some NaN values
# The names parameter sets the names for the levels in the index
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [np.nan, 20], [25, np.nan], [35, 40]],names=['a', 'b', 'c', 'd'])

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

# Drop the value when any level is NaN in a Multi-index
# Even with a single NaN value, the dropna() will drop all the values
# The "how" parameter of the dropna() is used with the value "any" for this
print("\nDropping the value when any level is NaN...\n",multiIndex.dropna(how='any'))

Output

This will produce the following output −

Multi-index...
MultiIndex([( 5, nan, 25.0, 35),(10, 20.0, nan, 40)],names=['a', 'b', 'c', 'd'])

Dropping the value when any level is NaN...
MultiIndex([], names=['a', 'b', 'c', 'd'])

Updated on: 13-Oct-2021

500 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements