📜  numpy rolling 2d - Python (1)

📅  最后修改于: 2023-12-03 15:33:14.176000             🧑  作者: Mango

Numpy Rolling 2D - Python

Numpy rolling function provides an easy way to perform rolling operations on n-dimensional arrays. The rolling function applies a rolling window to the array along a specific axis and then performs an operation on the window. In this article, we will discuss how to perform rolling operations on 2D arrays using numpy rolling 2D in Python.

Syntax

The syntax of numpy rolling 2D is as follows:

numpy.lib.stride_tricks.as_strided(arr, shape=(...), strides=(...))

Here, arr is the input 2D numpy array, shape is the output shape of the rolling window, and strides is the stride of the rolling window. The output of the rolling function is a view on the original array with the specified shape and strides.

Example

Let's consider an example to understand how to perform rolling operations on 2D arrays using numpy rolling 2D in Python.

import numpy as np

# Create a 2D numpy array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print("Input array:")
print(arr)

# Perform rolling operation along the rows
rolling_window = np.lib.stride_tricks.as_strided(arr, shape=(3, 2, 3), strides=(24, 8, 8))

# Print the rolling window
print("Result:")
print(rolling_window)

Output:

Input array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Result:
[[[1 2 3]
  [4 5 6]]

 [[4 5 6]
  [7 8 9]]

 [[7 8 9]
  [0 0 0]]]

In the above example, we have created a 2D numpy array and applied a rolling operation along the rows. The rolling window has a shape of (3, 2, 3), which means that there are three windows of size (2, 3) that rolls along the rows of the input array. The strides are (24, 8, 8), which means that the rolling window moves 24 bytes along the rows, 8 bytes along the columns and 8 bytes along the values.

Conclusion

In this article, we have discussed how to perform rolling operations on 2D arrays using numpy rolling 2D in Python. The rolling function is a powerful tool for manipulating n-dimensional arrays and can be used for a wide range of applications.