Skip to content
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

feat: add resample operator in post processing #16607

Merged
merged 5 commits into from
Sep 17, 2021
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
1 change: 1 addition & 0 deletions superset/charts/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,7 @@ class ChartDataPostProcessingOperationSchema(Schema):
"sort",
"diff",
"compare",
"resample",
)
),
example="aggregate",
Expand Down
26 changes: 26 additions & 0 deletions superset/utils/pandas_postprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -916,3 +916,29 @@ def outliers(series: Series) -> Set[float]:
for metric in metrics
}
return aggregate(df, groupby=groupby, aggregates=aggregates)


def resample(
df: DataFrame,
rule: str,
method: str,
time_column: str,
fill_value: Optional[Union[float, int]] = None,
) -> DataFrame:
"""
resample a timeseries dataframe.

:param df: DataFrame to resample.
:param rule: The offset string representing target conversion.
:param method: How to fill the NaN value after resample.
:param time_column: existing columns in DataFrame.
:param fill_value: What values do fill missing.
:return: DataFrame after resample
:raises QueryObjectValidationError: If the request in incorrect
"""
df = df.set_index(time_column)
if method == "asfreq" and fill_value is not None:
df = df.resample(rule).asfreq(fill_value=fill_value)
else:
df = getattr(df.resample(rule), method)()
return df.reset_index()
19 changes: 19 additions & 0 deletions tests/integration_tests/pandas_postprocessing_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,3 +870,22 @@ def test_boxplot_percentile_incorrect_params(self):
metrics=["cars"],
percentiles=[10, 90, 10],
)

def test_resample(self):
df = timeseries_df.copy()
df.index.name = "time_column"
df.reset_index(inplace=True)

post_df = proc.resample(
df=df, rule="1D", method="ffill", time_column="time_column",
)
self.assertListEqual(
post_df["label"].tolist(), ["x", "y", "y", "y", "z", "z", "q"]
)
self.assertListEqual(post_df["y"].tolist(), [1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 4.0])

post_df = proc.resample(
df=df, rule="1D", method="asfreq", time_column="time_column", fill_value=0,
)
self.assertListEqual(post_df["label"].tolist(), ["x", "y", 0, 0, "z", 0, "q"])
self.assertListEqual(post_df["y"].tolist(), [1.0, 2.0, 0, 0, 3.0, 0, 4.0])