admin管理员组

文章数量:1595880

一、pd.Period()创建时期

pd.Period()参数:一个时间戳 + freq 参数 → freq 用于指明该 period 的长度,时间戳则说明该 period 在时间轴上的位置

import pandas as pd

# pd.Period()创建时期

# 生成一个以2017-01开始,月为频率的时间构造器
# pd.Period()参数:一个时间戳 + freq 参数 → freq 用于指明该 period 的长度,时间戳则说明该 period 在时间轴上的位置
p1 = pd.Period('2017', freq='M')
print("p1 = {0}, type(p1) = {1}".format(p1, type(p1)))

# 通过加减整数,将周期整体移动
print("通过加减整数,将周期整体移动:p1 + 1 = ", p1 + 1)
print("通过加减整数,将周期整体移动:p1 + 2 = ", p1 + 2)
print("通过加减整数,将周期整体移动:p1 - 2 = ", p1 - 2)
print("-" * 100)
# 这里是按照 月、年 移动
p2 = pd.Period('2017', freq='A-DEC')
print("p2 = {0}, type(p2) = {1}".format(p2, type(p2)))
print("通过加减整数,将周期整体移动:p2 - 1 = ", p2 - 1)
print("通过加减整数,将周期整体移动:p2 - 2 = ", p2 - 2)
print("通过加减整数,将周期整体移动:p2 + 2 = ", p2 + 2)

打印结果:

p1 = 2017-01, type(p1) = <class 'pandas._libs.tslibs.period.Period'>
通过加减整数,将周期整体移动:p1 + 1 =  2017-02
通过加减整数,将周期整体移动:p1 + 2 =  2017-03
通过加减整数,将周期整体移动:p1 - 2 =  2016-11
----------------------------------------------------------------------------------------------------
p2 = 2017, type(p2) = <class 'pandas._libs.tslibs.period.Period'>
通过加减整数,将周期整体移动:p2 - 1 =  2016
通过加减整数,将周期整体移动:p2 - 2 =  2015
通过加减整数,将周期整体移动:p2 + 2 =  2019

Process finished with exit code 0

二、频率转换

通过.asfreq(freq, method=None, how=None)方法转换成别的频率

import pandas as pd

# asfreq:频率转换

period = pd.Period('2017', 'A-DEC')
print("period = ", period)
print("-" * 100)

# 通过.asfreq(freq, method=None, how=None)方法转换成别的频率
period1 = period.asfreq('M', how='start')  # 也可写 how = 's'
period2 = period.asfreq('D', how='end')  # 也可写 how = 'e'

print("period1 = ", period1)
print("-" * 50)
print("period2 = ", period2)
print("-" * 100)

打印结果:

period =  2017
----------------------------------------------------------------------------------------------------
period1 =  2017-01
--------------------------------------------------
period2 =  2017-12-31
----------------------------------------------------------------------------------------------------

Process finished with exit code 0

本文标签: 时期数据类型位置类型时间