简体   繁体   English

Cython:数组的内存高效填充

[英]Cython : memory-efficient padding of array

I have a M×N numpy array. 我有一个M×N numpy数组。 Before a FFT I need to pad it with zeros to get a (M+K)×(N+K) array where the M and N first indices are the original data and the K last indices along each dimension are zeros. 在进行FFT之前,我需要将其填充零以获得一个(M + K)×(N + K)数组,其中M和N个第一个索引是原始数据,而每个维度上的K个最后一个索引都是零。

Using Cython, is there an efficient way to do so without loosing the np.ndarray[DTYPE_t, ndim=2] type ? 使用Cython,是否有一种有效的方法可以做到这一点而又不会丢失np.ndarray[DTYPE_t, ndim=2]类型?

One way of padding an array is to create a target of the right size, and copy values: 填充数组的一种方法是创建大小合适的目标,并复制值:

In [137]: M,N,K = 10,20,5
In [138]: source = np.arange(M*N).reshape(M,N)
In [139]: target = np.zeros((M+K, N+K), dtype=source.dtype)
In [140]: target[:M, :N] = source

You can't get any more memory efficient than that. 您再也无法获得更高的内存效率。

I don't see how cython will help with memory use, since memory use is determined by the size of source and target arrays, not the coping method. 我不知道cython将如何帮助使用内存,因为内存使用取决于源数组和目标数组的大小,而不是应对方法。

I'm not even sure it will be faster, especially if you want target to be a numpy array that can be used in interpreted Python. 我什至不知道它会更快,特别是如果您希望target是可以在解释型Python中使用的numpy数组。 If both source and target are typed memoryview, the copy might be faster, but we'd have to test that. 如果源和目标都键入了memoryview,则副本可能会更快,但是我们必须对此进行测试。

The following will turn your array into a padded version without changing its type: 以下内容将在不更改数组类型的情况下将其变为填充版本:

array = np.hstack((array,np.zeros((np.size(array,0),K))))
array = np.vstack((array,np.zeros((K,np.size(array,1)))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM