重复 NumPy 数组而不复制数据? [英] Repeat NumPy array without replicating data?

查看:31
本文介绍了重复 NumPy 数组而不复制数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个一维 NumPy 数组,该数组由另一个一维数组的 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 行的二维数组,其中每一行都是你的第一个数组的一个视图,或者一个 flatiter 对象,它的行为有点像一维数组.(flatiters 支持迭代和索引,但您不能查看它们;所有索引都会复制.)

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)

二维视图:

b = np.lib.stride_tricks.as_strided(a, (1000, a.size), (0, a.itemsize))

扁平化对象:

c = b.flat

这篇关于重复 NumPy 数组而不复制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆