首页 文章资讯内容详情

Python Pandas - 返回一个包含来自 Index 对象的唯一值计数的系列,同时考虑 NaN 值

2026-06-03 1 花语

使用该方法返回包含来自Index对象的唯一值计数的系列,同时考虑NaN值。设置参数dropna值为index.value_counts()

首先,导入所需的库——

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

显示熊猫指数-

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

使用的唯一值计数value_counts()。考虑NaN以及使用“dropna”参数的“False”值-

index.value_counts(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) #返回索引中的元素数 print("\nNumber of elements in the index...\n",index.size) #返回数据的dtype print("\nThe dtype object...\n",index.dtype) #使用value_counts()计算唯一值 # considering NaN as well using the "False" 的价值 "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