首頁  >  文章  >  後端開發  >  為什麼 NumPy 沒有計算移動平均線的內建函數?

為什麼 NumPy 沒有計算移動平均線的內建函數?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 14:14:03637瀏覽

Why Doesn\'t NumPy Have a Built-in Function for Calculating Moving Averages?

Calculating Rolling / Moving Average with Python + NumPy / SciPy

despite the usefulness of moving averages in time series analysis, NumPy and SciPy do not offer a standalone function for this purpose, raising questions about the rationale behind this omission.

Implementing Moving Average in NumPy

One straightforward approach to implementing moving average in NumPy is through the np.cumsum function, which accumulates the elements of an array. The resulting cumsum array can then be appropriately sliced to obtain the moving average.

def moving_average(a, n=3):
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

This method is relatively fast and avoids error-prone convoluted solutions.

Reason for Lack of Batteries Included Functionality

Despite the apparent simplicity of the moving average implementation, the reason for its absence in NumPy core functionality is likely related to the specialized nature of such operations. NumPy focuses on providing fundamental numerical operations, while specialized algorithms like time series analysis are often left to dedicated packages. This approach allows NumPy to maintain its core functionality and avoids bloating it with niche tools.

以上是為什麼 NumPy 沒有計算移動平均線的內建函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn