How to Shift or Rotate an Array in Python

In this blog, we would discuss How to Shift or Rotate an Array in Python. To rotate an array in Python, use the collections module’s deque.rotate(n) method. The deque.rotate(n) method rotates the deque class object n times, where the sign of n determines whether the deque should be rotated left or right. If the value of n is positive, the input will be rotated from left to right. If the value of n is negative, the input will be rotated from right to left. Collections in Python are data containers that are usually known as data structures such as lists, tuples, arrays, dictionaries, and so on. Python includes a collections module that provides additional data structures for data collecting.

 

 

 

What is numpy.roll() function?

 

Using the supplied axis, the numpy.roll() function rolls array elements. The input array’s items are essentially shifted as a result of this. An element gets rolled back to the first position if it is moving from the first position to the final position. The array is rotated to positions equal to the shift value using the numpy.roll(array, shift, axis) method. If the array is two-dimensional, we must indicate which axis the rotation should be applied to. Otherwise, the rotation will be applied to both axes by the numpy.roll() method. The numpy.roll() method rotates the array in the same manner as the deque.rotate() method, rotating it to the right if the value is positive and to the left if it is negative. 

 

Parameters

 

Usage function: numpy.roll(ashiftaxis=None)

 

a: array_like – Input array.

shift: tuple of ints or an int – The number of shifts that elements undergo. Axis must be a tuple of the same size if it is a tuple, and each of the specified axes is shifted by the corresponding amount. The same value is utilised for each of the specified axes if an int while axis is a tuple of ints.

Axis: optional, int or tuple of ints – Elements are moved along an axis or axes. By default, the array is flattened before moving, and then it is restored to its original shape.

 

Implementation of How to Shift or Rotate an Array in Python

 

Python’s numpy.roll() method is used to rotate an array as shown in the example code below.

 

import numpy as np
  
array = np.arange(8).reshape(2, 4)
print("Original array : \n", array)
  
print("Rolling with 1 shift : \n", np.roll(array, 1))
 
print("Rolling with 5 shift : \n", np.roll(array, 5))

 

 

from collections import deque

myarray = deque([1, 2, 3, 4, 5, 6, 7, 8, 9])
myarray.rotate(4)
print(list(myarray))

 

 

Also read – How to Find First and Last Occurrence in a String

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *