Python Pandas - 从 Index 对象返回相对频率

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

要从 Index 对象返回相对频率,请使用 index.value_counts() 方法,并将参数 normalize 设置为 True。

首先,导入所需的库 -

import pandas as pd

创建 Pandas 索引 −

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

显示 Pandas 索引 −

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

使用 value_counts() 获取唯一值的数量。设置参数"normalize"为 True 以获取相对频率 −

print("\n通过将所有值除以值的总和来获取相对频率...\n", index.value_counts(normalize=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)

# 使用 value_counts() 获取唯一值的数量
# 将参数"normalize" 设置为 True 以获取相对频率
print("\n通过将所有值除以值的总和来获取相对频率...\n", index.value_counts(normalize=True))

输出

这将产生以下输出 −

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

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

dtype 对象...
int64

通过将所有值除以值的总和来获取相对频率...
50    0.222222
110   0.222222
90    0.222222
10    0.111111
70    0.111111
30    0.111111
dtype: float64

相关文章


有用资源