python pandas时序处理相关功能详解

yipeiwu_com6年前Python基础

创建时间序列

函数pd.date_range()

根据指定的范围,生成时间序列DatetimeIndex,每隔元素的类型为Timestamp。该函数应用较多。

ts = pd.date_range('2017-09-01', periods=10, freq='d', normalize=False)
ts

输出为:

DatetimeIndex(['2017-09-01', '2017-09-02', '2017-09-03', '2017-09-04',
'2017-09-05', '2017-09-06', '2017-09-07', '2017-09-08',
'2017-09-09', '2017-09-10'],
dtype='datetime64[ns]', freq='D'

主要的入参解析:

  • start: 开始时刻,可以是字符串或者datetime类型的值。默认None。
  • end: 结束时刻,可以是字符串或者datetime类型的值,如果指定了长度,即periods,则可不设置。默认None。
  • periods: 时序的长度,整型类型。如果有end,可不设置。默认None。
  • freq: 时序生成的频率,即每隔多少时刻生成一个时序点。字符串类型或者DateOffset类型。默认'D',即天粒度,见上述代码输出。
  • tz: 时区,字符串类型。默认None。
  • normalize: bool类型,没用过,不知道干啥的。
  • name: 设置时序的名称,字符串类型,默认None。
  • closed: 是否包含两边的值。默认None,即两边都保留。

其中,freq的取值可以为如下的符号表示间隔,可以结合符号和数字,如'3d',表示每隔三天记录一个时间点。大小写都可以。

B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds

字符串转换为时间戳

pd.to_datetime() 函数可以将表示时间的字符串转换位TimeStamp。

pd.to_datetime('2017-09-01')

输出为:

Timestamp('2017-09-01 00:00:00')

常用的参数:

format: 用来设置字符串的格式,默认如上所示。

时间戳的加减
有时候需要将时间进行增减,可以使用类型:DateOffset。

pd.to_datetime('2017-09-01') + pd.DateOffset(days=10) 

输出为:

Timestamp('2017-09-11 00:00:00')

DateOffset常用的参数:

  • months,设置月。
  • days,设置天。
  • years,设置年。
  • hours,设置小时。
  • minutes,设置分钟。
  • seconds,设置秒。

以上可以同时设置,组合使用。

pd.to_datetime('2017-09-01') + pd.DateOffset(seconds=10, days = 10)

输出为:

Timestamp('2017-09-11 00:00:10')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

wxPython电子表格功能wx.grid实例教程

本文实例为大家分享了wxPython电子表格功能的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python #encoding: utf8 import wx...

python numpy数组的索引和切片的操作方法

NumPy - 简介 NumPy 是一个 Python 包。 它代表 “Numeric Python”。 它是一个由多维数组对象和用于处理数组的例程集合组成的库。 Numeric,即 N...

Python基于动态规划算法计算单词距离

本文实例讲述了Python基于动态规划算法计算单词距离。分享给大家供大家参考。具体如下: #!/usr/bin/env python #coding=utf-8 def word_d...

Python读写Excel文件的实例

Python读写Excel文件的实例

最近由于经常要用到Excel,需要根据Excel表格中的内容对一些apk进行处理,手动处理很麻烦,于是决定写脚本来处理。首先贴出网上找来的读写Excel的脚本。 1.读取Excel(需要...

Python将8位的图片转为24位的图片实现方法

Python将8位的图片转为24位的图片实现方法

用的pytorch来训练deeplabv3+ 在做deeplabv3+的过程中,我的训练图片是8位的,如下图: 8位的: 24位的: 这样虽然在训练过程中能够正常训练。但是在评估过程...