Python Pandas - 返回一个包含从索引对象中唯一值计数的序列,同时考虑 NaN 值


使用 index.value_counts() 方法返回一个包含从索引对象中唯一值计数的序列,同时考虑 NaN 值。将参数 dropna 设置为值 False

首先导入所需的库 -

import pandas as pd
import numpy as np

创建一个带有一些 NaN 值的 Pandas 索引 −

index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])

显示 Pandas 索引 −

print("Pandas Index...\n",index)

使用 value_counts() 计数唯一值。使用“dropna”参数的“False”值同时考虑 NaN −

index.value_counts(dropna=False)

示例

以下是代码 −

import pandas as pd
import numpy as np

# Creating Pandas index with some NaN values as well
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# count of unique values using value_counts()
# considering NaN as well using the "False" value of the "dropna" parameter
print("\nGet the count of unique values with NaN...\n",index.value_counts(dropna=False))

输出

这将产生以下输出 −

Pandas Index...
Float64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64')

Number of elements in the index...
9

The dtype object...
float64

Get the count of unique values with NaN...
NaN   3
50.0  2
10.0  1
70.0  1
90.0  1
30.0  1
dtype: int64

更新于: 2021 年 10 月 13 日

142 次查看

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.