Python Pandas - 当多索引中的所有级别均为 NaN 时删除该值

要在 Multi-index 中的所有级别均为 NaN 时删除该值,请使用该方法。设置参数how与 value allmultiIndex.dropna()

首先,导入所需的库——

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

当 Multi-index 中的所有级别 iareNaN 时删除该值。对于所有 NaN 值,dropna()如果 的“how”参数dropna()设置为“all” ,则将删除所有值-

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

猜你喜欢