TimeSeriesDataFrame.convert_frequency¶
- TimeSeriesDataFrame.convert_frequency(freq: str | DateOffset, agg_numeric: str = 'mean', agg_categorical: str = 'first', num_cpus: int = -1, chunk_size: int = 100, **kwargs) TimeSeriesDataFrame[source]¶
将数据框中的每个时间序列转换为给定的频率。
此方法有两个用途:
将不规则采样的时间序列转换为规则的时间索引。
通过降采样聚合时间序列数据(例如,将每日销售额转换为每周销售额)
标准的
df.groupby(...).resample(...)对于大型数据集来说可能非常慢,因此我们将其操作并行化到多个CPU核心上。- Parameters:
freq (Union[str, pd.DateOffset]) – 数据应转换的频率。支持的取值请参见 pandas 频率别名。
agg_numeric ({"max", "min", "sum", "mean", "median", "first", "last"}, default = "mean") – 应用于数值列的聚合方法。
agg_categorical ({"first", "last"}, default = "first") – 应用于分类列的聚合方法。
num_cpus (int, default = -1) – 并行重采样时使用的CPU核心数。设置为-1以使用所有核心。
chunk_size (int, default = 100) – 分配给每个并行工作者的时间序列块中的时间序列数量。
**kwargs – 将传递给
pandas.DataFrameGroupBy.resample的额外关键字参数。
- Returns:
ts_df – 一个新的时间序列数据框,其中时间序列已按新频率重新采样。如果原始数据在给定时间段内没有信息,则输出可能包含由
NaN表示的缺失值。- Return type:
示例
将不规则采样的时间序列数据转换为规则索引
>>> ts_df target item_id timestamp 0 2019-01-01 NaN 2019-01-03 1.0 2019-01-06 2.0 2019-01-07 NaN 1 2019-02-04 3.0 2019-02-07 4.0 >>> ts_df.convert_frequency(freq="D") target item_id timestamp 0 2019-01-01 NaN 2019-01-02 NaN 2019-01-03 1.0 2019-01-04 NaN 2019-01-05 NaN 2019-01-06 2.0 2019-01-07 NaN 1 2019-02-04 3.0 2019-02-05 NaN 2019-02-06 NaN 2019-02-07 4.0
将季度数据下采样为年度频率
>>> ts_df target item_id timestamp 0 2020-03-31 1.0 2020-06-30 2.0 2020-09-30 3.0 2020-12-31 4.0 2021-03-31 5.0 2021-06-30 6.0 2021-09-30 7.0 2021-12-31 8.0 >>> ts_df.convert_frequency("YE") target item_id timestamp 0 2020-12-31 2.5 2021-12-31 6.5 >>> ts_df.convert_frequency("YE", agg_numeric="sum") target item_id timestamp 0 2020-12-31 10.0 2021-12-31 26.0