Python Pandas - 将 Period 转换为所需频率
pythonserver side programmingprogramming更新于 2026/1/25 10:20:17
要将 Period 转换为所需频率,请使用 period.asfreq() 方法。假设我们将使用 ‘H’ 说明符设置为所需的每小时频率。
首先,导入所需的库 −
import pandas as pd
pandas.Period 表示一段时间。创建两个 Period 对象
period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2,minute = 35)
显示 Period 对象
print("Period1...\n", period1)
print("Period2...\n", period2)
将 Period 转换为所需频率。我们将频率设置为 H,即每小时频率
res1 = period1.asfreq('H')
res2 = period2.asfreq('H')
示例
以下是代码
import pandas as pd
# pandas.Period 表示一段时间
# 创建两个 Period 对象
period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, 分钟 = 35)
# 显示 Period 对象
print("Period1...\n", period1)
print("Period2...\n", period2)
# 将 Period 转换为所需频率
# 我们将频率设置为 H,即每小时频率
res1 = period1.asfreq('H')
res2 = period2.asfreq('H')
# 从两个 Period 对象返回年份
print("\n从第一个 Period 对象转换后的结果...\n", res1)
print("\n从第二个 Period 对象转换后的结果...\n", res2)
输出
将生成以下代码
Period1... 2020-09-23 03:15:40 Period2... 2021-04-16 从第一个 Period 对象转换后的结果... 2020-09-23 03:00 从第二个 Period 对象转换后的结果... 2021-04-16 23:00
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

