首页 文章资讯内容详情

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

2026-06-03 1 花语

要从Index对象返回相对频率,请使用参数normalizeTrue的方法。index.value_counts()

首先,导入所需的库——

import pandas as pd

创建熊猫索引-

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

显示熊猫指数-

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

使用获取唯一值的计数value_counts()。将参数“normalize”设置为True以获取相对频率-

print("\nGet the relative frequency by dividing all values by the sum of values...\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("\nNumber of elements in the index...\n",index.size) #返回数据的dtype print("\nThe dtype object...\n",index.dtype) #使用value_counts()获取唯一值的计数 # Set the parameter "normalize" to True to get the relative frequency print("\nGet the relative frequency by dividing all values by the sum of values...\n", index.value_counts(normalize=True))输出结果

这将产生以下输出-

Pandas Index... Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype=int64) Number of elements in the index... 9 The dtype object... int64 Get the relative frequency by dividing all values by the sum of values... 50 0.222222 110 0.222222 90 0.222222 10 0.111111 70 0.111111 30 0.111111 dtype: float64