| 109 | |
| 110 | |
| 111 | def _pandas(mode, trendline_options, x_raw, y, non_missing): |
| 112 | import numpy as np |
| 113 | |
| 114 | try: |
| 115 | import pandas as pd |
| 116 | except ImportError: |
| 117 | msg = "Trendline requires pandas to be installed" |
| 118 | raise ImportError(msg) |
| 119 | |
| 120 | modes = dict(rolling="Rolling", ewm="Exponentially Weighted", expanding="Expanding") |
| 121 | trendline_options = trendline_options.copy() |
| 122 | function_name = trendline_options.pop("function", "mean") |
| 123 | function_args = trendline_options.pop("function_args", dict()) |
| 124 | |
| 125 | series = pd.Series(np.copy(y), index=x_raw.to_pandas()) |
| 126 | |
| 127 | # TODO: Narwhals Series/DataFrame do not support rolling, ewm nor expanding, therefore |
| 128 | # it fallbacks to pandas Series independently of the original type. |
| 129 | # Plotly issue: https://github.com/plotly/plotly.py/issues/4834 |
| 130 | # Narwhals issue: https://github.com/narwhals-dev/narwhals/issues/1254 |
| 131 | agg = getattr(series, mode) # e.g. series.rolling |
| 132 | agg_obj = agg(**trendline_options) # e.g. series.rolling(**opts) |
| 133 | function = getattr(agg_obj, function_name) # e.g. series.rolling(**opts).mean |
| 134 | y_out = function(**function_args) # e.g. series.rolling(**opts).mean(**opts) |
| 135 | y_out = y_out[non_missing] |
| 136 | hover_header = "<b>%s %s trendline</b><br><br>" % (modes[mode], function_name) |
| 137 | return y_out, hover_header, None |
| 138 | |
| 139 | |
| 140 | def rolling(trendline_options, x_raw, x, y, x_label, y_label, non_missing): |