Pythonic way to access shifted version of numpy array?

What is the pythonic way to access shifted, right or left arrays numpy? A vivid example:

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

Is access available:

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

from the library numpy?

+4
source share
1 answer

Are you looking for np.roll-

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

Run Example -

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

If you want more changes, just go np.roll(a,-2)and np.roll(a,2)etc.

+4
source

Source: https://habr.com/ru/post/1654249/


All Articles