Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do circular shift in numpy

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.

like image 865
LWZ Avatar asked Apr 03 '13 16:04

LWZ


People also ask

How do you shift a circle in Python?

Using Collection deque This method allows us to shift by n elements ahead at once, using both directions, forward and backward. We just need to use the rotate method on the deque object. Note, that you can easily convert a deque object to a list like list(x) where x is a deque object.

How do you shift elements in a NumPy array?

To shift the bits of integer array elements to the right, use the numpy. right_shift() method in Python Numpy. Bits are shifted to the right x2. Because the internal representation of numbers is in binary format, this operation is equivalent to dividing x1 by 2**x2.

How do I rotate an image in NumPy?

Rotate image with NumPy: np. The NumPy function that rotates ndarray is np. rot90() . Specify the original ndarray as the first argument and the number of times to rotate 90 degrees as the second argument.

What is NumPy Ogrid?

NumPy: ogrid() function index_tricks. nd_grid which returns an open (i.e. not fleshed out) mesh-grid when indexed, so that only one dimension of each returned array is greater than 1. The dimension and number of the output arrays are equal to the number of indexing dimensions.


2 Answers

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])
like image 177
mgilson Avatar answered Oct 10 '22 22:10

mgilson


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]

like image 8
Francesco Montesano Avatar answered Oct 10 '22 23:10

Francesco Montesano