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'])

更新於: 13-Oct-2021

666 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.