重复 NumPy 数组而不复制数据?
我想创建一个 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.
Is it possible?
If it helps, I intend to treat both arrays as immutable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能这样做; NumPy 数组必须沿每个维度具有一致的步幅,而您的步幅大多数时候需要朝一个方向走,但有时会向后跳。
您可以获得的最接近的是 1000 行二维数组,其中每一行都是第一个数组的视图,或者
flatiter
对象,其行为有点像一维数组。 (Flatiters 支持迭代和索引,但您无法获取它们的视图;所有索引都会生成副本。)设置:
2D 视图:
Flatiter 对象:
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.
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.)Setup:
2D view:
flatiter object:
broadcast_to
已在 numpy 1.10 中添加,这可以让您以更少的努力有效地重复数组。复制已接受答案的样式:
broadcast_to
was added in numpy 1.10, which allows you effectively repeat an array with a little less effort.Copying the style of the accepted answer:
我不是 100% 确定“不复制数据 1000 次”是什么意思。如果您正在寻找一种 numpy 方法来从
a
一次性构建b
(而不是循环),您可以使用:否则,我会执行以下操作:
<在这种情况下,code>b 不是
a
的视图,因为它有精美的索引(它创建了一个副本),但至少它返回一个 numpy 数组并且不会创建 1000 *内存中的 1000x1 数组,仅包含您想要的元素。至于它们是不可变的(请参阅 不可变的 numpy 数组?),您需要单独切换每个标志,因为副本不保留标志设置。
I'm not 100% sure what you mean by 'not replicating the data 1000 times'. If you are looking for a numpy method to build
b
froma
in one fell swoop (rather than looping), you can use:Otherwise, I would do something like:
b
is not a view ofa
in this case because of the fancy indexing (it makes a copy), but at least it returns a numpy array and doesn't create the 1000*1000x1 array in memory and just contains the elements you want.As far as them being immutable (see Immutable numpy array?), you would need to switch the flag for each separately since copies don't retain the flag setting.
我并不认为这是最优雅的解决方案,因为您必须欺骗 numpy 创建对象数组(请参阅带有注释的行)
I do not claim that this is the most elegant solution, because you have to fool numpy into creating an array of objects (see the line with the comment)
这行得通吗:
Would this work: