Skip to content

feat: Add Series.autocorr #605

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bigframes/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,9 @@ def corr(self, other: Series, method="pearson", min_periods=None) -> float:
)
return self._apply_binary_aggregation(other, agg_ops.CorrOp())

def autocorr(self, lag: int = 1) -> float:
return self.corr(self.shift(lag))

def cov(self, other: Series) -> float:
return self._apply_binary_aggregation(other, agg_ops.CovOp())

Expand Down
8 changes: 8 additions & 0 deletions tests/system/small/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,14 @@ def test_series_corr(scalars_dfs):
assert math.isclose(pd_result, bf_result)


@skip_legacy_pandas
def test_series_autocorr(scalars_dfs):
scalars_df, scalars_pandas_df = scalars_dfs
bf_result = scalars_df["float64_col"].autocorr(2)
pd_result = scalars_pandas_df["float64_col"].autocorr(2)
assert math.isclose(pd_result, bf_result)


def test_series_cov(scalars_dfs):
scalars_df, scalars_pandas_df = scalars_dfs
bf_result = scalars_df["int64_too"].cov(scalars_df["int64_too"])
Expand Down
32 changes: 32 additions & 0 deletions third_party/bigframes_vendored/pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,38 @@ def corr(self, other, method="pearson", min_periods=None) -> float:
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)

def autocorr(self, lag: int = 1) -> float:
"""
Compute the lag-N autocorrelation.

This method computes the Pearson correlation between
the Series and its shifted self.

**Examples:**
>>> import bigframes.pandas as bpd
>>> bpd.options.display.progress_bar = None

>>> s = bpd.Series([0.25, 0.5, 0.2, -0.05])
>>> s.autocorr() # doctest: +ELLIPSIS
0.10355...
>>> s.autocorr(lag=2)
-1.0

If the Pearson correlation is not well defined, then 'NaN' is returned.

>>> s = bpd.Series([1, 0, 0, 0])
>>> s.autocorr()
nan

Args:
lag (int, default 1):
Number of lags to apply before performing autocorrelation.

Returns:
float: The Pearson correlation between self and self.shift(lag).
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)

def cov(
self,
other,
Expand Down