使用列表索引numpy数组时避免复制 [英] Avoid copying when indexing a numpy arrays using lists

查看:87
本文介绍了使用列表索引numpy数组时避免复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以使用列表或任何其他集合对数组进行索引,以便不进行任何复制(仅获取数组的视图).请不要尝试按照下面的代码片段来回答问题---我用来索引元素的列表并不总是很短(即数千个元素,而不是4个),并且该列表是算法和因此,数字不一定必须排序,等等.

Is there a simple way to index arrays using lists or any other collection so that no copy is made (just a view of the array is taken). Please do not try to answer the question in terms of the snippet of code below --- the list I use to index the element is not always short (i.e. thousands of elements, not 4) and the list is a product of an algorithm and hence the number are not necessarily ordered, etc.

例如,在两种情况下均在下面的代码中选择了第1,2和3列,但仅在第一种情况下才返回数据视图:

For example in the code below columns 1,2 and 3 are selected in both cases but only in the first case a view of the data is returned:

>>> a[:,1:4]
>>> b = a[:,1:4]
>>> b.base is a
True
>>> c = a[:,[1,3,2]]
>>> c.base is a
False

推荐答案

花式索引(使用索引列表访问数组的元素)始终会产生一个副本,因为numpy无法将其转换为新的副本从特定元素开始的相同数据视图,但具有固定的步幅和形状.

Fancy indexing (using a list of indices to access elements of an array) always produces a copy, as there is no way for numpy to translate it into a new view of the same data, but with a different fixed stride and shape, starting from a particular element.

在内部,numpy数组是指向数组内存中第一个元素的指针,dtype,形状以及有关在内存中移动到各个维度(下一行,下一列等)的距离的信息)和一些标志.关于某些预先存在的内存的视图仅指向该数组中的某个元素,并以步幅和形状来摆弄.花式索引通常指定对先前存在的内存的随机访问,并且您不能强制将数据转换为必要的格式,因此必须进行复制.

Under the hood, a numpy array is a pointer to the first element in memory of an array, a dtype, shape and information about how far to move in memory to get to each of the dimensions (next row, column, etc) and some flags. A view on some pre-existing memory just points to some element in that array and fiddles with the stride and shape. Fancy indexing generally specifies random access into that pre-existing memory and you can't force that data into the necessary form, so a copy has to be made.

这篇关于使用列表索引numpy数组时避免复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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