- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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'])
Advertisements