
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Drop Values with NaN in Multi-Index using Python Pandas
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'])
Advertisements