Pandas-时期(一)-数据类型:Period(时期类型)【创建:pd.Period(value=‘2017‘, freq=‘M‘)->Period】【value:该period在时间轴上的位置】

一、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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值