Python 如何在numpy中进行循环移位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15792465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to do circular shift in numpy
提问by LWZ
I have a numpy array, for example
例如,我有一个 numpy 数组
a = np.arange(10)
how can I move the first nelements to the end of the array?
如何将第一个n元素移动到数组的末尾?
I found this rollfunction but it seems like it only does the opposite, which shifts the last nelements to the beginning.
我找到了这个roll函数,但它似乎只做相反的事情,将最后一个n元素移到开头。
采纳答案by mgilson
Why not just rollwith a negative number?
为什么不只是roll一个负数?
>>> import numpy as np
>>> a = np.arange(10)
>>> np.roll(a,2)
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
>>> np.roll(a,-2)
array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
回答by Francesco Montesano
you can use negative shift
你可以使用负移
a = np.arange(10)
print(np.roll(a, 3))
print(np.roll(a, -3))
returns
返回
[7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
[7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]

