使用 numpy.apply

发布于 2024-08-27 06:48:35 字数 428 浏览 3 评论 0原文

这段代码有什么问题?

import numpy as np
from scipy import stats

d = np.arange(10.0)
cutoffs = [stats.scoreatpercentile(d, pct) for pct in range(0, 100, 20)]
f = lambda x: np.sum(x > cutoffs)
fv = np.vectorize(f)

# why don't these two lines output the same values?
[f(x) for x in d] # => [0, 1, 2, 2, 3, 3, 4, 4, 5, 5]
fv(d)             # => array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

有什么想法吗?

What's wrong with this snippet of code?

import numpy as np
from scipy import stats

d = np.arange(10.0)
cutoffs = [stats.scoreatpercentile(d, pct) for pct in range(0, 100, 20)]
f = lambda x: np.sum(x > cutoffs)
fv = np.vectorize(f)

# why don't these two lines output the same values?
[f(x) for x in d] # => [0, 1, 2, 2, 3, 3, 4, 4, 5, 5]
fv(d)             # => array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一页 2024-09-03 06:48:35

cutoffs 是一个列表。从 d 中提取的数字全部转换为 float 并使用 numpy.vectorize 应用。 (这实际上很奇怪——看起来它首先尝试像你想要的那样工作的 numpy 浮点数,然后尝试正常的 Python 浮点数。)通过 Python 中相当奇怪、愚蠢的行为,浮点数总是小于列表,所以不要得到类似的东西

>>> # Here is a vectorized array operation, like you get from numpy. It won't
>>> # happen if you just use a float and a list.
>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]
[True, True, False, False, False] # not real

为了

>>> # This is an actual copy-paste from a Python interpreter
>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]
False

解决这个问题,你可以将 cutoffs 设为 numpy 数组而不是 list。 (您可能也可以将比较完全转移到 numpy 操作中,而不是用 numpy.vectorize 来伪造它,但我不知道。)

cutoffs is a list. The numbers you extract from d are all turned into float and applied using numpy.vectorize. (It's actually rather odd—it looks like first it tries numpy floats that work like you want then it tries normal Python floats.) By a rather odd, stupid behavior in Python, floats are always less than lists, so instead of getting things like

>>> # Here is a vectorized array operation, like you get from numpy. It won't
>>> # happen if you just use a float and a list.
>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]
[True, True, False, False, False] # not real

you get

>>> # This is an actual copy-paste from a Python interpreter
>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]
False

To solve the problem, you can make cutoffs a numpy array instead of a list. (You could probably also move the comparison into numpy operations entirely instead of faking it with numpy.vectorize, but I do not know offhand.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文