gpt4 book ai didi

python - 一维 ndarray 的高效 fenceposting

转载 作者:太空宇宙 更新时间:2023-11-04 09:00:32 26 4
gpt4 key购买 nike

使用 numpydata reshape 为 fencepost 的最有效方法是什么?

data      = np.array([1, 2, 3, 4, 5])                                                             
fencepost = np.array([[1, 2], [2, 3], [3, 4], [4, 5]])

最佳答案

只需以不同的方式查看相同的数据,即可获得相同的结果:

>>> from numpy.lib.stride_tricks import as_strided
>>> fencepost = as_strided(data, shape=(data.shape[0]-1, 2),
strides=(data.strides[0],)*2)
>>> fencepost
array([[1, 2],
[2, 3],
[3, 4],
[4, 5]])

没有数据被复制,所以特别是对于非常大的阵列,这将尽可能快。如果您确实需要一个单独的副本,您可以简单地执行 fencepost = fencepost.copy() 并让 numpy 在内部为您处理一切:

In [11]: data = np.arange(10000000)

In [12]: %timeit as_strided(data, shape=(data.shape[0]-1, 2),
... strides=(data.strides[0],)*2)
100000 loops, best of 3: 12.2 us per loop

In [13]: %timeit as_strided(data, shape=(data.shape[0]-1, 2),
... strides=(data.strides[0],)*2).copy()
10 loops, best of 3: 183 ms per loop

关于python - 一维 ndarray 的高效 fenceposting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25896917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com