栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

快速numpy滚动_产品

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

快速numpy滚动_产品

我有一个更快的机制,尽管您需要运行一些测试以查看准确性是否足够。

这是原始的exp / sum / log版本:

def rolling_prod1(xs, n):    return np.exp(pd.rolling_sum(np.log(xs), n))

这是一个使用累积乘积,将其移过(用nans预先填充),然后将其重新分配出去的版本。

def rolling_prod2(xs, n):    cxs = np.cumprod(xs)    nans = np.empty(n)    nans[:] = np.nan    nans[n-1] = 1.    a = np.concatenate((nans, cxs[:len(cxs)-n]))    return cxs / a

对于此示例,两个函数返回相同的结果:

In [9]: xsOut[9]: array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])In [10]: rolling_prod1(xs, 3)Out[10]: array([  nan,   nan,    6.,   24.,   60.,  120.,  210.,  336.,  504.])In [11]: rolling_prod2(xs, 3)Out[11]: array([  nan,   nan,    6.,   24.,   60.,  120.,  210.,  336.,  504.])

但是第二个版本要快得多:

In [12]: temp_col = np.random.rand(30000)In [13]: %timeit rolling_prod1(temp_col, 3)1000 loops, best of 3: 694 µs per loopIn [14]: %timeit rolling_prod2(temp_col, 3)10000 loops, best of 3: 162 µs per loop


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633731.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号