Skip to main content
 首页 » 编程设计

python之使用 numpy.apply

2025年05月04日22softidea

这段代码有什么问题?

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]) 

有什么想法吗?

请您参考如下方法:

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

>>> # 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 伪造它,但我不知道。)