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 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始
广告