使用 numpy.apply
这段代码有什么问题?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
cutoffs
是一个列表。从d
中提取的数字全部转换为float
并使用numpy.vectorize
应用。 (这实际上很奇怪——看起来它首先尝试像你想要的那样工作的 numpy 浮点数,然后尝试正常的 Python 浮点数。)通过 Python 中相当奇怪、愚蠢的行为,浮点数总是小于列表,所以不要得到类似的东西为了
解决这个问题,你可以将
cutoffs
设为 numpy 数组而不是list
。 (您可能也可以将比较完全转移到 numpy 操作中,而不是用 numpy.vectorize 来伪造它,但我不知道。)cutoffs
is a list. The numbers you extract fromd
are all turned intofloat
and applied usingnumpy.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 likeyou get
To solve the problem, you can make
cutoffs
a numpy array instead of alist
. (You could probably also move the comparison into numpy operations entirely instead of faking it withnumpy.vectorize
, but I do not know offhand.)