📜  numpy rolling - Python (1)

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

NumPy Rolling - Python

NumPy is the fundamental package for scientific computing in Python. It provides powerful tools to manipulate arrays and perform mathematical operations on them. One of the useful functions provided by NumPy is the rolling function.

What is NumPy Rolling?

The rolling function is used to apply a rolling window calculation to a numpy array. It takes an input array and applies a function over a rolling window of a fixed size. The function calculates the value over the window and moves the window by a specified number of steps.

Syntax

The syntax of the rolling function is as follows:

numpy.rolling(a, window, axis=None)

Here, a is the input array, window is the size of the rolling window, and axis is the axis along which the window should operate. If axis is not provided, the function operates over the last dimension of the input array.

Example

Let's see an example of how to use the rolling function:

import numpy as np

# Creating input array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# Applying rolling function
rolling_arr = np.rolling(arr, 3)

# Displaying result
print(rolling_arr)

Output:

[[nan nan  1.]
 [nan  1.  2.]
 [ 1.  2.  3.]
 [ 2.  3.  4.]
 [ 3.  4.  5.]
 [ 4.  5.  6.]
 [ 5.  6.  7.]
 [ 6.  7.  8.]
 [ 7.  8.  9.]
 [ 8.  9. 10.]]

In this example, we created an input array using the np.array function. Then, we applied the rolling function with a window size of 3. This means that the function applied a rolling window of size 3 over the input array.

The output of the rolling function is a new array with the rolling window calculation values.

Conclusion

In conclusion, the rolling function provided by NumPy is a simple and useful tool for performing rolling window calculations on numpy arrays. It is an easy-to-use function that can be applied to a variety of data analysis tasks.