Python Pandas - 返回包含按升序排序的 Index 对象中唯一值计数的 Series

pythonserver side programmingprogramming更新于 2025/12/29 13:00:17

要返回包含按升序排序的 Index 对象中唯一值计数的 Series,请使用 index.value_counts() 方法,并将参数 ascending 设置为 True。

首先,导入所需的库 -

import pandas as pd

创建 Pandas 索引 −

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

显示Pandas 索引 −

print("Pandas 索引...\n",index)

按升序排列的唯一值计数 −

print("\n获取按升序排列的唯一值计数.​​.." "\n",index.value_counts(ascending=True))

示例

以下是代码 −

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(ascending=True))

输出

这将产生以下输出 −

Pandas Index...
Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64')

索引中的元素数量...
9

dtype 对象...
int64

获取按升序排列的唯一值的数量...
10   1
70   1
30   1
50   2
110  2
90   2
dtype: int64

相关文章


有用资源