pandas
时间
转换
看过来
《pandas 教程》 持续更新中,可作为 pandas 入门进阶课程、pandas 中文手册、用法大全,配有案例讲解和速查手册。提供建议、纠错、催更等加作者微信: gairuo123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。查看更新日志。作者开办 Python 数据分析培训,详情 Python 数据分析培训。
![]() |
本教程作者所著新书《深入浅出Pandas:利用Python进行数据处理与分析》(ISBN:9787111685456)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
本文介绍不同时间概念之间的相互转换。带时间戳的数据可以使用 to_period 转换为PeriodIndex-ed 数据,反之亦然可以使用 to_timestamp 转换为 PeriodIndex-ed 数据。
rng = pd.date_range('1/1/2012', periods=5, freq='M')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts
'''
2012-01-31 1.931253
2012-02-29 -0.184594
2012-03-31 0.249656
2012-04-30 -0.978151
2012-05-31 -0.873389
Freq: M, dtype: float64
'''
ps = ts.to_period()
ps
'''
2012-01 1.931253
2012-02 -0.184594
2012-03 0.249656
2012-04 -0.978151
2012-05 -0.873389
Freq: M, dtype: float64
'''
ps.to_timestamp()
'''
2012-01-01 1.931253
2012-02-01 -0.184594
2012-03-01 0.249656
2012-04-01 -0.978151
2012-05-01 -0.873389
Freq: MS, dtype: float64
'''
“s”和“ e”可用于返回时间段开始或结束时的时间戳:
ps.to_timestamp('D', how='s')
'''
2012-01-01 1.931253
2012-02-01 -0.184594
2012-03-01 0.249656
2012-04-01 -0.978151
2012-05-01 -0.873389
Freq: MS, dtype: float64
'''
在周期和时间戳之间转换可以使用一些方便的算术函数。 在以下示例中,我们将以11月结束的年度的季度频率转换为季度结束后的月末的上午9点:
prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')
ts = pd.Series(np.random.randn(len(prng)), prng)
ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
ts.head()
'''
1990-03-01 09:00 -0.109291
1990-06-01 09:00 -0.637235
1990-09-01 09:00 -1.735925
1990-12-01 09:00 2.096946
1991-03-01 09:00 -1.039926
Freq: H, dtype: float64
'''
无「盖若」授权,请勿以任何形式转载,公众号:gairuo
Copyright © 2019 - 2023
Gairuo.com All Rights Reserved v7.2.0.0403
京公网安备11010502033395号
京ICP备15019454号-4