预分配NumPy数组的首选方法是什么? [英] What is the preferred way to preallocate NumPy arrays?
问题描述
我是NumPy/SciPy的新手.从文档中看,预分配似乎更有效 单个数组,而不是调用append/insert/concatenate.
I am new to NumPy/SciPy. From the documentation, it seems more efficient to preallocate a single array rather than call append/insert/concatenate.
例如,要将1的列添加到数组中,我认为是这样的:
For example, to add a column of 1's to an array, i think that this:
ar0 = np.linspace(10, 20, 16).reshape(4, 4)
ar0[:,-1] = np.ones_like(ar0[:,0])
首选:
ar0 = np.linspace(10, 20, 12).reshape(4, 3)
ar0 = np.insert(ar0, ar0.shape[1], np.ones_like(ar0[:,0]), axis=1)
我的第一个问题是这是否正确(第一个更好),而我的第二个问题是,目前,我只是像这样预先分配我的数组(我在SciPy上的一些Cookbook示例中注意到了这一点)网站):
my first question is whether this is correct (that the first is better), and my second question is, at the moment, I am just preallocating my arrays like this (which I noticed in several of the Cookbook examples on the SciPy Site):
np.zeros((8,5))
首选NumPy"的方式是什么?
what is the 'NumPy-preferred' way to do this?
推荐答案
预分配m在一次调用中分配您需要的所有内存,而调整数组大小(通过调用append,insert,concatenate或resize的大小)可能需要将数组复制到更大的内存块.因此,您是对的,预分配比调整大小更可取(并且应该比调整大小更快).
Preallocation mallocs all the memory you need in one call, while resizing the array (through calls to append,insert,concatenate or resize) may require copying the array to a larger block of memory. So you are correct, preallocation is preferred over (and should be faster than) resizing.
根据您要创建的内容,有许多首选"方法可以预分配numpy数组.有np.zeros
,np.ones
,np.empty
,np.zeros_like
,np.ones_like
和np.empty_like
,还有许多其他创建有用的数组的文件,例如np.linspace
和np.arange
.
There are a number of "preferred" ways to preallocate numpy arrays depending on what you want to create. There is np.zeros
, np.ones
, np.empty
, np.zeros_like
, np.ones_like
, and np.empty_like
, and many others that create useful arrays such as np.linspace
, and np.arange
.
所以
ar0 = np.linspace(10, 20, 16).reshape(4, 4)
如果
最接近您想要的ar0
,就很好.
但是,要使最后一栏全为1,我认为首选的方法是说
However, to make the last column all 1's, I think the preferred way would be to just say
ar0[:,-1]=1
由于ar0[:,-1]
的形状为(4,)
,因此1为广播以匹配此形状
Since the shape of ar0[:,-1]
is (4,)
, the 1 is broadcasted to match this shape.
这篇关于预分配NumPy数组的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!