如何转换/移动一个numpy数组? [英] How to translate / shift a numpy array?
问题描述
我不确定要搜索什么关键字,因此如果已经被询问,请链接响应并关闭该线程.
I am not sure what key-word to search for so if it has been already asked please link the response and close this thread.
我正在尝试将numpy数组的非零条目按固定方向移动,例如,假设我有一个2d数组:
I am trying to shift the non-zero entries of a numpy array by a fixed direction, for instance, imagine I have a 2d array:
0 1 2 0
0 3 0 0
0 0 0 0
0 0 0 0
将其移动(1,1)将产生以下数组:
Shifting it by (1,1) would produce the following array:
0 0 0 0
0 0 1 2
0 0 3 0
0 0 0 0
让我们说如果非零条目超出范围,则将它们简单地丢弃.我该怎么办?
Let's say if the non-zero entries goes out of bound they're simply dropped. How might I do this?
显然与此有些重复? 移动numpy数组中的元素 我真的看不出它们为什么是一个完全相同的问题,因为那个人谈论的是使事情无限循环,所以这更多的是滚动"动作而不是转移.我也喜欢这里的解决方案,它非常简单易读.
edit: aparently some duplicate from this? Shift elements in a numpy array I don't really see why are they the same question at all because that one talks about looping the things out of bound around, so it's more of a "rolling" action rather than shifting. Also I liked the solution here, it is very simple and readable.
再次修复了某些格式
推荐答案
要简单地管理边缘,可以将数组扩大到更大:
To simply manage the edges, you can enlarge your array in a bigger one :
square=\
array([[0, 2, 2, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int64)
n,m=square.shape
bigsquare=np.zeros((3*n,3*m),square.dtype)
bigsquare[n:2*n,m:2*m]=square
然后转移只是一个视图:
Then shift is just a view :
def shift(dx,dy):
x=n-dx
y=m-dy
return bigsquare[x:x+n,y:y+m]
print(shift(1,1))
#[[0 0 0 0]
# [0 0 2 2]
# [0 0 2 0]
# [0 0 0 0]]
这篇关于如何转换/移动一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!