how to do circular shift in numpy

匆匆过客 提交于 2019-12-21 07:27:33

问题


I have a numpy array, for example

a = np.arange(10)

how can I move the first n elements to the end of the array?

I found this roll function but it seems like it only does the opposite, which shifts the last n elements to the beginning.


回答1:


Why not just roll with a negative number?

>>> 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])



回答2:


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]



来源:https://stackoverflow.com/questions/15792465/how-to-do-circular-shift-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!