简单滚动平均:前几个值的处理及自定义函数优化咨询
Hey there! Let's tweak your rolling average function to handle those initial shorter windows—you're already halfway there with that commented-out logic. Since you're avoiding external libraries like NumPy/Pandas, we can adjust the existing code with straightforward Python loops.
First, let's finish up your mean function (it looks like it got cut off) to avoid runtime errors:
def mean(lst): if not lst: return 0.0 # Edge case protection, though we won't hit this scenario here return sum(lst) / len(lst)
Now, let's adjust get_rolling_average to calculate averages for every position, even when the window hasn't reached full period length yet. There are two common approaches here, depending on what you want for those initial values:
Option 1: Cumulative Average (Start-to-Current)
This uses all elements from the start of the dataset up to the current position for the initial values, then switches to the full period window once we have enough data. This matches the logic you hinted at in your comments:
def get_rolling_average(data, period): rolling = [] for i in range(len(data)): if i < period - 1: # For the first (period-1) elements, use all data from start to current nums = data[:i+1] else: # Once we have enough data, use the full rolling window nums = data[i - period + 1:i+1] # Calculate mean and optionally round it to clean decimal places avg = mean(nums) rolling.append(round_nicely(avg, 2)) # Adjust the decimal places as needed return rolling
Option 2: Strict Sliding Window (Most Recent Elements)
If you prefer that even initial windows only use the most recent elements (instead of all prior data), we can simplify the logic to always take up to period elements ending at the current position:
def get_rolling_average(data, period): rolling = [] for i in range(len(data)): # Calculate the start of the window—never go before the first element window_start = max(0, i - period + 1) nums = data[window_start:i+1] avg = mean(nums) rolling.append(round_nicely(avg, 2)) return rolling
For example, if data = [1,2,3,4,5] and period=3:
- Option 1 returns
[1.0, 1.5, 2.0, 3.0, 4.0](cumulative averages for the first two positions, then full window averages) - Option 2 produces the same result here, but for longer datasets, it will always stick to the most recent
periodelements once past the initial phase.
Your round_nicely function works perfectly as-is for rounding results to a clean number of decimal places:
def round_nicely(num, places): return round(num, places)
Testing this with your sample data should give you the full set of rolling averages you're looking for!
内容的提问来源于stack exchange,提问作者Ghoul Fool

