在numpy的交换阵列数据 [英] Swap Array Data in NumPy

查看:363
本文介绍了在numpy的交换阵列数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个算法使用了许多大型多维数组的NP(2D和3D)。有无数的迭代在此,并在每次迭代期间阵列通过进行计算和保存到相同大小的临时数组重新计算。在单次迭代结束时的临时数组的内容被复制到实际的数据数组。

I have many large multidimensional NP arrays (2D and 3D) used in an algorithm. There are numerous iterations in this, and during each iteration the arrays are recalculated by performing calculations and saving into temporary arrays of the same size. At the end of a single iteration the contents of the temporary arrays are copied into the actual data arrays.

例如:

global A, B # ndarrays
A_temp = numpy.zeros(A.shape)
B_temp = numpy.zeros(B.shape)
for i in xrange(num_iters):
    # Calculate new values from A and B storing in A_temp and B_temp...
    # Then copy values from temps to A and B
    A[:] = A_temp
    B[:] = B_temp

这工作得很好,但它似乎有点浪费,当A和B可以只换复制所有这些值。下面将交换阵​​列:

This works fine, however it seems a bit wasteful to copy all those values when A and B could just swap. The following would swap the arrays:

A, A_temp = A_temp, A
B, B_temp = B_temp, B

然而,有可能在其他领域的阵列而这不会改变其他的引用。

However there can be other references to the arrays in other scopes which this won't change.

这似乎是numpy的可以有一个内部的方法交换两个数组,如 numpy.swap(A,A_temp)的内部数据指针。然后指着 A 所有变量将指向更改的数据。

It seems like NumPy could have an internal method for swapping the internal data pointer of two arrays, such as numpy.swap(A, A_temp). Then all variables pointing to A would be pointing to the changed data.

推荐答案

也许你可以通过添加一个间接层面解决这个问题。

Perhaps you could solve this by adding a level of indirection.

您可以有一个阵列持有人类。所有这一切会做的是保持对基础numpy的数组的引用。一对这些实施廉价的交换操作将是微不足道的。

You could have an "array holder" class. All that would do is keep a reference to the underlying NumPy array. Implementing a cheap swap operation for a pair of these would be trivial.

如果所有外部引用这些对象持有人,而不是直接到阵列,没有这些引用会得到由交换无效。

If all external references are to these holder objects and not directly to the arrays, none of those references would get invalidated by a swap.

这篇关于在numpy的交换阵列数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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