将NumPy数组的大小调整为较小的大小,而不进行复制 [英] Resize NumPy array to smaller size without copy

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

问题描述

当我使用resize方法缩小一个numpy数组时(即由于resize,该数组变得更小),是否可以保证不进行任何复制?

When I shrink a numpy array using the resize method (i.e. the array gets smaller due to the resize), is it guaranteed that no copy is made?

示例:

a = np.arange(10)            # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a.resize(5, refcheck=False)  # array([0, 1, 2, 3, 4])

根据我的理解,这应该总是可以实现的,而无需复制.我的问题:实施过程是否确实可以保证始终如此?不幸的是,调整大小的文档对此一无所获

From my understanding this should always be possible without making a copy. My question: Does the implementation indeed guarantee that this is always the case? Unfortunately the documentation of resize says nothing about it.

推荐答案

numpy数组在后台是固定大小的数组,任何类型的调整大小将始终复制该数组.

A numpy array is a fixed size array in the background, any type of resizing will always copy the array.

话虽如此,您仅使用数组的一个子集就可以有效地创建数组的一部分,而无需调整大小/复制.

Having that said, you could create a slice of the array effectively only using a subset of the array without having to resize/copy.

>>> import numpy
>>> a = numpy.arange(10)
>>> b = a[:5]
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b
array([0, 1, 2, 3, 4])
>>>
>>> a += 10
>>> a
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> b
array([10, 11, 12, 13, 14])
>>>
>>> b += 10
>>> a
array([20, 21, 22, 23, 24, 15, 16, 17, 18, 19])
>>> b
array([20, 21, 22, 23, 24])

这篇关于将NumPy数组的大小调整为较小的大小,而不进行复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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