将相同的numpy数组的两个视图合并到单个视图中而不复制该数组? [英] Combining two views of same numpy array into single view without copying the array?

查看:93
本文介绍了将相同的numpy数组的两个视图合并到单个视图中而不复制该数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的2d numpy数组,我想删除它的子集并处理函数剩余的内容.我需要对许多子集执行此操作,因此理想情况下,我不想每次都创建数组的副本.该函数不会更改数组中的任何值.

I have a large 2d numpy array and I want to remove subsets of it and handle what remains to a function. I need to do this for many subsets, and thus I would ideally not want to create a copy of the array each time. The function doesn't change any values in the array.

mat = np.load(filename)
mat_1 = mat[:i,:]
mat_2 = mat[j:,:]

到目前为止,mat_1和mat_2是视图. 那我想做

So far, mat_1 and mat_2 are views. Then I would like to do

mat_s = np.concatenate((mat_1,mat_2))
result = func(mat_s)

,但不进行复制.这可能吗?

but without making a copy. Is this possible?

推荐答案

由于只能使用一组固定的strides创建内存视图,因此您必须在您的情况下创建一个副本,其中mat.shape[0] > j > i.

Since memory-views can only be created using a fixed set of strides, you will have to create a copy in your case, where mat.shape[0] > j > i.

这意味着,仅当您要查看数组中每个第x个元素的视图时,视图才起作用:

That means views will only work, if you want to have a view to every x-th element in the array:

mat = np.arange(20)
view = mat[slice(0, 20, 4)]
view
# Out[41]: array([ 0,  4,  8, 12, 16])

因此,这仅适用于等距单元格的视图.但是,如果要查看一个连续的slice(0, i)和另一个连续的slice(j, mat.shape[0]),则将无法使用.您必须进行复制.

So this only works for views to equally spaced cells. But if you want to have a view to one contiguous slice(0, i) and another contiguous slice(j, mat.shape[0]), it won't work. You'll have to make a copy.

这篇关于将相同的numpy数组的两个视图合并到单个视图中而不复制该数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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