如何使用 series.asfreq() 方法转换 TimeSeries?

阅读 141 收藏 0 点赞 0 评论 0

大熊猫。方法用于将时间序列转换为指定的频率。通过使用此方法的参数,我们也可以填充值。Series.asfreq()missing(null)

它将返回一个具有重新索引频率的系列对象,该频率是通过asfreq()方法指定的。方法的参数asfreq()是freq,method=None,how=None,normalize=False,fill_value=None。除了 freq 其余所有参数都有默认值。

让我们使用 pandas date_range 模块创建一个时间序列对象并应用该asfreq()方法。

示例 1

import pandas as pd

# create the index
index = pd.date_range('2021-07-01', periods=10, freq='H')

#creating pandas Series with date index
series = pd.Series([1,3,None,5,7,9,None,2,3,4], index=index)

print(series)

# converted time series
print("Converted time series",series.asfreq(freq='2H'))

解释

最初,我们使用 python import 关键字将 pandas 模块导入到我们的工作区,然后我们使用 date range 函数创建了一个带有时间序列数据的索引变量,之后,我们创建了一个带有时间序列的 pandas 系列对象。

输出结果

2021-07-01 00:00:00 1.0
2021-07-01 01:00:00 3.0
2021-07-01 02:00:00 NaN
2021-07-01 03:00:00 5.0
2021-07-01 04:00:00 7.0
2021-07-01 05:00:00 9.0
2021-07-01 06:00:00 NaN
2021-07-01 07:00:00 2.0
2021-07-01 08:00:00 3.0
2021-07-01 09:00:00 4.0
Freq: H, dtype: float64

Converted time series
2021-07-01 00:00:00 1.0
2021-07-01 02:00:00 NaN
2021-07-01 04:00:00 7.0
2021-07-01 06:00:00 NaN
2021-07-01 08:00:00 3.0
Freq: 2H, dtype: float64

初始时间序列由 10 个周期创建,频率为小时。显示在上述输出块的第一部分。

并且转换后的时间序列对象也显示在上面的输出块中,其中频率转换为 2 小时。结果系列中只有 5 个元素。

示例 2

import pandas as pd

# create the index
index = pd.date_range('2021-06-30', periods=10, freq='M')

#creating pandas Series with date index
series = pd.Series(index.month_name(), index=index)

print(series)

# converted time series
print("Converted time series",series.asfreq(freq='Q'))

解释

在上面的示例中,我们使用 Date_range 方法创建了一个熊猫系列,该方法具有 10 个月份的频率。之后,我们将系列对象的频率更改为每季度一次。

输出结果

2021-06-30      June
2021-07-31      July
2021-08-31    August
2021-09-30 September
2021-10-31   October
2021-11-30  November
2021-12-31  December
2022-01-31   January
2022-02-28  February
2022-03-31     March
Freq: M, dtype: object

Converted time series
2021-06-30      June
2021-09-30 September
2021-12-31  December
2022-03-31     March
Freq: Q-DEC, dtype: object

在上面的输出块中,我们可以看到初始时间序列对象和转换的时间序列对象。通过将“Q”值提供给 asfreq 方法的“freq”参数,转换后的时间序列更新为季度频率。

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号