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

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

问题描述

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

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

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

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

但是,即使 this 代码也无法正确交换值!这是因为Numpy 切片并不急于复制数据,他们将视图创建到现有数据中.仅在分配切片时执行复制,但是在交换时,没有中间缓冲区的复制会破坏您的数据.这就是为什么您不仅需要一个附加变量,而且还需要一个附加的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天全站免登陆