Python Pandas - 当多索引中的任何级别为 NaN 时删除该值

要在多索引中的任何级别为 NaN 时删除该值,请使用该方法。使用值any设置参数howmultiIndex.dropna()

首先,导入所需的库——

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”参数dropna()与值“any”一起使用 -

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

猜你喜欢