Python NumPy Shift Array
This tutorial will introduce methods for shifting NumPy arrays.
np.roll()
NumPy Shift Arrays Using the
If we want to shift the elements of a NumPy array right or left, we can use the numpy.roll() method in Python. The roll() numpy.roll()
method is used to roll the elements of an array along the specified axis. It accepts the array and the number of positions by which we want to shift the elements of the array and returns the shifted array. If we want to shift the elements to the right, we have to use a positive integer as the shift value. If we want to shift the elements to the left, we have to specify a negative shift value. The following code example shows how to numpy.roll()
shift the elements of an array using the roll() method.
import numpy as np
array = np.array([1, 2, 3, 4, 5])
array_new = np.roll(array, 3)
print(array_new)
Output:
[3 4 5 1 2]
We first np.array()
created the array using the function. Then we np.roll()
shifted the elements to the right using the function and stored the resulting array in array_new
.
NumPy Shift Array and Slicing Methods in Python
If we want to shift elements to the right or left and replace the shifted indices with constant values, we have to use array slicing method in Python. We can create a new empty array just like the original array. If the shift value is positive, we fill the left side of the array with the constant value, and if the shift value is negative, we fill the right side of the array with the constant value. Then we can fill the remaining indices of the new array with the values from the original array. The following code example shows how to shift the elements of an array using array slicing method.
import numpy as np
array = np.array([1, 2, 3, 4, 5])
num = -3
fill_value = 0
def shift(arr, num, fill_value):
result = np.empty_like(arr)
if num > 0:
result[:num] = fill_value
result[num:] = arr[:-num]
elif num < 0:
result[num:] = fill_value
result[:num] = arr[-num:]
else:
result[:] = arr
print(result)
shift(array, num, fill_value)
Output:
[4 5 0 0 0]
We defined the function shift()
that shifts the elements of an array to the left by three positions using the array slicing method in the code above. We first np.array()
created our original array using the shift_by method. We then specified the number of indices we wanted to shift the array elements by num
and the constant value we wanted to replace all the shifted indices with fill_value
. Finally, we passed these values to shift()
the shift_by function, which np.empty_like(arr)
created a new array using the shift_by function result
just like our original array, stored the shifted elements, and printed the shifted array.
NumPy Shift Arrays scipy.ndimage.interpolation
with Shift function in Python libraryshift()
scipy.ndimage.interpolation
The shift() method in the library is used to shift an array using the spline interpolation method in Python. Unlike numpy.roll()
the method, the shift shift()
() method can shift an array and replace the shifted indexes with the specified constant value at the same time. shift()
The shift() function takes as input parameters the original array, the number of indexes we want to shift, and the constant value we want to replace with the shifted indexes, and returns the shifted array where each shifted index is replaced with the specified constant value. The following code example shows us how to shift()
shift the elements of an array using the shift() function.
import numpy as np
from scipy.ndimage.interpolation import shift
array = np.array([1, 2, 3, 4, 5])
result = shift(array, 3, cval=0)
print(result)
Output:
[0 0 0 1 2]
We shifted the elements of by three positions to the right and replaced the shifted indices with using the shift function array
in the code above . We first created our array using the shift function. We then shifted to the right by positions using the shift function and replaced the first three indices of the original array with the constant value . We stored the output of the shift function in the array. Finally, we printed the values in the array.shift()
0
np.array()
array
3
0
shift()
result
result
All of these methods work fine. If we only want to shift the values within the array and do not want to replace the shifted indices with constant values, we should use numpy.roll()
the shift() function. On the other hand, if we want to replace the shifted indices with specific constant values, the array slicing method is the fastest way to do this operation. The array slicing method is faster but a bit more complicated than using the shift() function scipy
from the Array library shift()
. If we do not care about the performance of the code, we can use shift()
the shift() function to accomplish this task.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Convert Tensor to NumPy array in Python
Publish Date:2025/05/03 Views:85 Category:Python
-
This tutorial will show you how to convert a Tensor to a NumPy array in Python. Use the function in Python Tensor.numpy() to convert a tensor to a NumPy array Eager Execution of TensorFlow library can be used to convert tensor to NumPy arra
Saving NumPy arrays as images in Python
Publish Date:2025/05/03 Views:193 Category:Python
-
In Python, numpy module is used to manipulate arrays. There are many modules available in Python that allow us to read and store images. An image can be thought of as an array of different pixels stored at specific locations with correspond
Transposing a 1D array in NumPy
Publish Date:2025/05/03 Views:98 Category:Python
-
Arrays and matrices form the core of this Python library. The transpose of these arrays and matrices plays a vital role in certain topics such as machine learning. In NumPy, it is easy to calculate the transpose of an array or a matrix. Tra
Find the first index of an element in a NumPy array
Publish Date:2025/05/03 Views:58 Category:Python
-
In this tutorial, we will discuss how to find the first index of an element in a numpy array. Use where() the function to find the first index of an element in a NumPy array The function in the numpy module where() is used to return an arra
Remove Nan values from NumPy array
Publish Date:2025/05/03 Views:118 Category:Python
-
This article discusses some built-in NumPy functions that you can use to remove nan values. Remove Nan values using logical_not() and methods in NumPy isnan() logical_not() is used to apply logical NOT to the elements of an array. isn
Normalizing a vector in Python
Publish Date:2025/05/03 Views:51 Category:Python
-
A common concept in the field of machine learning is to normalize a vector or dataset before passing it to the algorithm. When we talk about normalizing a vector, we say that its vector magnitude is 1, being a unit vector. In this tutorial,
Calculating Euclidean distance in Python
Publish Date:2025/05/03 Views:128 Category:Python
-
In the world of mathematics, the shortest distance between two points in any dimension is called the Euclidean distance. It is the square root of the sum of the squares of the differences between the two points. In Python, the numpy, scipy
Element-wise division in Python NumPy
Publish Date:2025/05/03 Views:199 Category:Python
-
This tutorial shows you how to perform element-wise division on NumPy arrays in Python. NumPy Element-Wise Division using numpy.divide() the function If we have two arrays and want to divide each element of the first array with each element
Convert 3D array to 2D array in Python
Publish Date:2025/05/03 Views:79 Category:Python
-
In this tutorial, we will discuss the methods to convert 3D array to 2D array in Python. numpy.reshape() Convert 3D array to 2D array using function in Python [ numpy.reshape() Function](numpy.reshape - NumPy v1.20 manual)Changes the shape