重复NumPy数组而不复制数据? [英] Repeat NumPy array without replicating data?
问题描述
我想创建一个1D NumPy数组,该数组由另一个1D数组的1000次背对背重复组成,而无需将数据复制1000次.
I'd like to create a 1D NumPy array that would consist of 1000 back-to-back repetitions of another 1D array, without replicating the data 1000 times.
有可能吗?
如果有帮助,我打算将两个数组都视为不可变的.
If it helps, I intend to treat both arrays as immutable.
推荐答案
您不能执行此操作;一个NumPy数组在每个维度上必须具有一致的步幅,而您的步幅在大多数情况下都需要采用一种方式,但有时会向后跳.
You can't do this; a NumPy array must have a consistent stride along each dimension, while your strides would need to go one way most of the time but sometimes jump backwards.
您可以获得的最接近的结果是一个1000行的2D数组,其中每一行都是您第一个数组的视图,或者是
The closest you can get is either a 1000-row 2D array where every row is a view of your first array, or a flatiter
object, which behaves kind of like a 1D array. (flatiters support iteration and indexing, but you can't take views of them; all indexing makes a copy.)
设置:
import numpy as np
a = np.arange(10)
2D视图:
b = np.lib.stride_tricks.as_strided(a, (1000, a.size), (0, a.itemsize))
flatiter对象:
flatiter object:
c = b.flat
这篇关于重复NumPy数组而不复制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!