@@ -2525,6 +2525,86 @@ def mode(self: Self) -> Self:
2525
2525
"""
2526
2526
return self ._from_compliant_series (self ._compliant_series .mode ())
2527
2527
2528
+ def rolling_mean (
2529
+ self : Self ,
2530
+ window_size : int ,
2531
+ weights : list [float ] | None = None ,
2532
+ * ,
2533
+ min_periods : int | None = None ,
2534
+ center : bool = False ,
2535
+ ) -> Self :
2536
+ """
2537
+ Apply a rolling mean (moving mean) over the values of the series.
2538
+
2539
+ A window of length `window_size` will traverse the series. The values that fill
2540
+ this window will (optionally) be multiplied with the weights given by the
2541
+ `weight` vector. The resulting values will be aggregated to their mean.
2542
+
2543
+ The window at a given row will include the row itself and the `window_size - 1`
2544
+ elements before it.
2545
+
2546
+ Arguments:
2547
+ window_size: The length of the window in number of elements.
2548
+ weights: An optional slice with the same length as the window that will be
2549
+ multiplied elementwise with the values in the window.
2550
+ min_periods: The number of values in the window that should be non-null before
2551
+ computing a result. If set to `None` (default), it will be set equal to
2552
+ `window_size`.
2553
+ center: Set the labels at the center of the window.
2554
+
2555
+ Examples:
2556
+ >>> import narwhals as nw
2557
+ >>> import pandas as pd
2558
+ >>> import polars as pl
2559
+ >>> import pyarrow as pa
2560
+
2561
+ >>> data = [100, 200, 300]
2562
+ >>> s_pd = pd.Series(name="a", data=data)
2563
+ >>> s_pl = pl.Series(name="a", values=data)
2564
+ >>> s_pa = pa.chunked_array([data])
2565
+
2566
+ We define a library agnostic function:
2567
+
2568
+ >>> @nw.narwhalify
2569
+ ... def func(s):
2570
+ ... return s.rolling_mean(window_size=2)
2571
+
2572
+ We can then pass any supported library such as Pandas, Polars, or PyArrow to `func`:
2573
+
2574
+ >>> func(s_pd)
2575
+ 0 NaN
2576
+ 1 150.0
2577
+ 2 250.0
2578
+ Name: a, dtype: float64
2579
+
2580
+ >>> func(s_pl) # doctest:+NORMALIZE_WHITESPACE
2581
+ shape: (3,)
2582
+ Series: 'a' [f64]
2583
+ [
2584
+ null
2585
+ 150.0
2586
+ 250.0
2587
+ ]
2588
+
2589
+ >>> func(s_pa) # doctest:+ELLIPSIS
2590
+ <pyarrow.lib.ChunkedArray object at ...>
2591
+ [
2592
+ [
2593
+ null,
2594
+ 150,
2595
+ 250
2596
+ ]
2597
+ ]
2598
+ """
2599
+ return self ._from_compliant_series (
2600
+ self ._compliant_series .rolling_mean (
2601
+ window_size = window_size ,
2602
+ weights = weights ,
2603
+ min_periods = min_periods ,
2604
+ center = center ,
2605
+ )
2606
+ )
2607
+
2528
2608
def __iter__ (self : Self ) -> Iterator [Any ]:
2529
2609
yield from self ._compliant_series .__iter__ ()
2530
2610
0 commit comments