交换 Numpy 数组的切片 [英] Swap slices of Numpy arrays

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

问题描述

我喜欢 python 处理变量交换的方式:a, b, = b, a

I love the way python is handling swaps of variables: a, b, = b, a

而且我也想使用此功能在数组之间交换值,不仅一次一个,而是多个(不使用临时变量).这不是我所期望的(我希望第三维的两个条目都可以交换):

and I would like to use this functionality to swap values between arrays as well, not only one at a time, but a number of them (without using a temp variable). This does not what I expected (I hoped both entries along the third dimension would swap for both):

import numpy as np
a = np.random.randint(0, 10, (2, 3,3))
b = np.random.randint(0, 10, (2, 5,5))
# display before
a[:,0, 0]
b[:,0,0]
a[:,0,0], b[:, 0, 0] = b[:, 0, 0], a[:,0,0] #swap
# display after
a[:,0, 0]
b[:,0,0]

有人有想法吗?当然我总是可以引入一个额外的变量,但我想知道是否有更优雅的方法来做到这一点.

Does anyone have an idea? Of course I can always introduce an additional variable, but I was wondering whether there was a more elegant way of doing this.

推荐答案

Python 正确地解释了代码,就像您使用了附加变量一样,因此交换代码等效于:

Python correctly interprets the code as if you used additional variables, so the swapping code is equivalent to:

t1 = b[:,0,0]
t2 = a[:,0,0]
a[:,0,0] = t1
b[:,0,0] = t2

然而,即使这个代码也不能正确交换值!这是因为 Numpy slices 并不急切复制数据,他们在现有数据中创建视图.复制仅在分配切片时执行,但在交换时,没有中间缓冲区的复制会破坏您的数据.这就是为什么您不仅需要一个额外的变量,还需要一个额外的 numpy 缓冲区,而一般 Python 语法对此一无所知.例如,这按预期工作:

However, even this code doesn't swap values correctly! This is because Numpy slices don't eagerly copy data, they create views into existing data. Copies are performed only at the point when slices are assigned to, but when swapping, the copy without an intermediate buffer destroys your data. This is why you need not only an additional variable, but an additional numpy buffer, which general Python syntax can know nothing about. For example, this works as expected:

t = np.copy(a[:,0,0])
a[:,0,0] = b[:,0,0]
b[:,0,0] = t

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

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