pd.expanding_mean已弃用:咨询替代方案及弃用原因
Hey there! Those FutureWarnings are pandas' way of nudging you away from an old API toward better, more consistent tools. Let's cover the replacements for pd.expanding_mean and why it's being phased out.
Alternatives to pd.expanding_mean
For pandas Series or DataFrames
The modern, preferred replacement is the chainable .expanding().mean() method. This fits seamlessly with pandas' current window operation pattern:
import pandas as pd # Sample data df = pd.DataFrame({'values': [10, 20, 30, 40, 50]}) # Deprecated approach # pd.expanding_mean(df['values']) # New, supported approach df['values'].expanding().mean()
This returns the same expanding mean result but uses pandas' standardized window API, which works with other aggregations too (like .sum(), .std()) if you need them later.
For NumPy ndarrays
If you're working directly with numpy arrays, you have two solid options:
- Wrap the array in a pandas Series first, then use the expanding mean method:
import numpy as np arr = np.array([10, 20, 30, 40, 50]) expanding_mean = pd.Series(arr).expanding().mean().to_numpy() - Use numpy's built-in functions to calculate it manually (great if you want to avoid pandas entirely):
cumulative_sums = np.cumsum(arr) counts = np.arange(1, len(arr) + 1) expanding_mean = cumulative_sums / counts
Why pd.expanding_mean Was Deprecated
There are three key reasons pandas decided to phase out this function:
- API Consistency: Pandas has shifted to a modular window API (
.expanding(),.rolling(),.ewm()) that returns a window object. You then apply aggregation functions to this object, which makes the code more readable and consistent across different window operations.pd.expanding_meanwas a one-off function that broke this pattern. - Reduced Redundancy: Instead of having separate functions like
pd.expanding_mean,pd.expanding_sum,pd.expanding_std, etc., the new API lets you use a single.expanding()call with any aggregation method. This cleans up the pandas namespace and makes it easier to learn. - Streamlined Support for ndarrays: Pandas' core focus is on its own Series and DataFrame structures. Direct support for ndarrays in the old expanding functions was removed to simplify the codebase. Wrapping an array in a Series (as shown above) is the intended way to handle this now, keeping things aligned with pandas' design principles.
内容的提问来源于stack exchange,提问作者Daniel Chepenko

