Python Pandas – 返回Index对象的相对频率
要返回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("\n数据类型对象...\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
数据类型对象...
int64
通过将所有值除以值的总和来获取相对频率...
50 0.222222
110 0.222222
90 0.222222
10 0.111111
70 0.111111
30 0.111111
dtype: float64
极客教程