Python Pandas - 从 Index 对象返回包含唯一值计数的 Series
pythonserver side programmingprogramming更新于 2025/12/29 12:28:17
要从 Index 对象返回包含唯一值计数的 Series,请使用 Pandas 中的 index.value_counts() 方法。
首先,导入所需的库 -
import pandas as pd
创建 Pandas 索引 −
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
显示 Pandas 索引 −
print("Pandas Index...\n",index)
唯一值计数 −
print("\n获取唯一值计数...\n",index.value_counts())
示例
以下是代码 −
import pandas as pd
# 创建 Pandas 索引
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
# 显示 Pandas 索引
print("Pandas Index...\n",index)
# 返回索引中的元素数量
print("\n索引中的元素数量...\n",index.size)
# 返回数据的 dtype
print("\ndtype 对象...\n",index.dtype)
# 唯一值的数量
print("\n获取唯一值的数量...\n",index.value_counts())
输出
这将产生以下输出 −
Pandas Index... Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64') 索引中的元素数量... 9 dtype 对象... int64 获取唯一值的数量... 50 2 110 2 90 2 10 1 70 1 30 1 dtype: int64
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

