访问numpy数组的平移版本的Pythonic方式是什么?

4
什么是访问一个numpy数组向右或向左移位的pythonic方法?以下是一个明确的示例:
a = np.array([1.0, 2.0, 3.0, 4.0])

有没有办法访问:

a_shifted_1_left = np.array([2.0, 3.0, 4.0, 1.0])

来自于numpy库?

1个回答

3

You are looking for np.roll -

np.roll(a,-1) # shifted left
np.roll(a,1) # shifted right

示例运行 -

In [28]: a
Out[28]: array([ 1.,  2.,  3.,  4.])

In [29]: np.roll(a,-1) # shifted left
Out[29]: array([ 2.,  3.,  4.,  1.])

In [30]: np.roll(a,1) # shifted right
Out[30]: array([ 4.,  1.,  2.,  3.])

如果您想要更多的转移,只需执行np.roll(a,-2)np.roll(a,2)等操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接