Python Pandas - 當多級索引的所有級別均為 NaN 時刪除值


若要刪除多級索引中值,當所有級別都是 NaN 時,請使用 multiIndex.dropna() 方法。使用值設定引數how all

首先,匯入所需的庫 -

import pandas as pd
import numpy as np

使用所有 NaN 值建立多級索引。names 引數設定索引中各級名稱 −

multiIndex = pd.MultiIndex.from_arrays([[np.nan, np.nan], [np.nan, np.nan]],
names=['a', 'b'])

當所有級別在多級索引中為 NaN 時,刪除值。如果 dropna() 的“how”引數設定為“all”,則所有 NaN 值將被 dropna() 刪除 −

print("\nDropping the values when all levels are NaN...\n",multiIndex.dropna(how='all'))

例項

程式碼如下 −

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

輸出

將產生以下輸出 −

Multi-index...
MultiIndex([(nan, nan),(nan, nan)],names=['a', 'b'])

Dropping the values when all levels are NaN...
MultiIndex([], names=['a', 'b'])

更新於: 13-Oct-2021

877 人檢視

開啟你的 職業

透過完成課程獲取認證

立即開始
廣告
© . All rights reserved.