Python Pandas - 当多索引中的任何级别为 NaN 时删除该值
要在多索引中的任何级别为 NaN 时删除该值,请使用该方法。使用值any设置参数how。multiIndex.dropna()
首先,导入所需的库——
import pandas as pdimport 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'])
以上是 Python Pandas - 当多索引中的任何级别为 NaN 时删除该值 的全部内容, 来源链接: utcz.com/z/322629.html