Python Pandas - 在多級索引中刪除任意一個級別為 NaN 的值
若要在多級索引中刪除任意一個級別為 NaN 的值,請使用 multiIndex.dropna() 方法。將引數 how 設定為 any。
首先,匯入所需的庫 -
import pandas as pd import numpy as np
建立一個帶有 NaN 值的多級索引。names 引數設定索引中各級別的名稱 -
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [np.nan, 20], [25, np.nan], [35, 40]],names=['a', 'b', 'c', 'd'])
刪除多級索引中任意一個級別為 NaN 的值。即使只存在一個 NaN 值,dropna() 也會刪除所有值。“how”引數與 “any”一起用於 dropna() -
print("\nDropping the value when any level is NaN...\n",multiIndex.dropna(how='any'))範例
以下為程式碼 -
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'))輸出
將產生以下輸出 -
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'])
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP