python - 规范化数字列表时,结果全为零

标签 python

我需要对列表中的值进行归一化以生成(累积)概率分布,但目前我只是得到 0。

这是我正在做的:

tests = []
#some code to populate tests which simulates
count = [x[0] for x in tests]
found = [x[1] for x in tests]
found.sort()
num = Counter(found)
freqs = [x for x in num.values()]
cumsum = [sum(item for item in freqs[0:rank+1]) for rank in xrange(len(freqs))]
normcumsum  = [float(x/numtests) for x in cumsum]

目前 cumsum 和 normcumsum 是:

cumsum = [1, 2, 6, 12, 28, 39, 64, 85, 96, 98, 99, 100]
normcumsum = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]

如何让 normcumsum 包含 cumsum/100?

N>B 是的,这些变量名有点傻。

最佳答案

x/numtests 将始终返回 0,很像 1/2 将始终返回 0,因为您正在进行整数除法

你必须做float(x)/numtests,或者做:

from __future__ import division

这只在 python2 中是必需的,在 python3 中不是必需的。

演示:

>>> [1/2, 3/2, 5/2]
[0, 1, 2]

>>> from __future__ import division

>>> [1/2, 3/2, 5/2]
[0.5, 1.5, 2.5]

关于python - 规范化数字列表时,结果全为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17728232/

相关文章:

python - 如何仅在 z3 中解决此问题

python - 在同一单元格中绘制图

python - 如何使用自连接来 reshape Pandas 中的重复行?

python - 在 3d 中绘制隐式方程

python - 比较 Pandas 中的日期范围

python - 将数据帧保存到多个保留数据帧名称的 CSV

python - 如何根据 Pandas 中一系列列的特定条件选择行

python - 为不同版本的python升级pip

python - 如何编写一个 python 程序,从给定的下拉菜单中选择所有可能的组合,从网站上获取结果 'scrapes' ?

python - python中困惑的值范围