在 pandas 中使用日期与时间

Python 中的时间序列数据处理

Stefan Jansen

Founder & Lead Data Scientist at Applied Artificial Intelligence

日期与时间序列功能

  • 核心:日期与时间数据类型
    • 表示时间点与期间的对象
    • 属性与方法体现时间细节
  • 日期与期间的序列:
    • 作为 Series 或 DataFrame 列
    • 作为索引:将对象转为时间序列
  • 许多 Series/DataFrame 方法依赖索引中的时间信息提供时序功能
Python 中的时间序列数据处理

基础构件:pd.Timestamp

import pandas as pd  # assumed imported going forward
from datetime import datetime  # To manually create dates

time_stamp = pd.Timestamp(datetime(2017, 1, 1))
pd.Timestamp('2017-01-01') == time_stamp
True # Understands dates as strings
time_stamp # type: pandas.tslib.Timestamp
Timestamp('2017-01-01 00:00:00')
Python 中的时间序列数据处理

基础构件:pd.Timestamp

  • Timestamp 对象包含丰富的时间属性
time_stamp.year
2017
time_stamp.day_name()
'Sunday'
Python 中的时间序列数据处理

更多基础:pd.Period 与 freq

period = pd.Period('2017-01')

period # default: month-end
Period('2017-01', 'M')
period.asfreq('D') # convert to daily
Period('2017-01-31', 'D')
period.to_timestamp().to_period('M')
Period('2017-01', 'M')

 

  • Period 对象通过 freq 属性存储频率信息

 

  • pd.Period()pd.Timestamp() 之间互转
Python 中的时间序列数据处理

更多基础:pd.Period 与 freq

period + 2
Period('2017-03', 'M')
pd.Timestamp('2017-01-31', 'M') + 1
Timestamp('2017-02-28 00:00:00', freq='M')
  • 频率信息支持基本日期运算
Python 中的时间序列数据处理

日期与时间序列

  • pd.date_rangestartendperiodsfreq
index = pd.date_range(start='2017-1-1', periods=12, freq='M')
index
DatetimeIndex(['2017-01-31', '2017-02-28', '2017-03-31', ...,
               '2017-09-30', '2017-10-31', '2017-11-30', '2017-12-31'],
              dtype='datetime64[ns]', freq='M')
  • pd.DateTimeIndex:带频率信息的 Timestamp 序列
Python 中的时间序列数据处理

日期与时间序列

index[0]
Timestamp('2017-01-31 00:00:00', freq='M')
index.to_period()
PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', ..., 
             '2017-11', '2017-12'], dtype='period[M]', freq='M')
Python 中的时间序列数据处理

创建时间序列:pd.DateTimeIndex

pd.DataFrame({'data': index}).info()
RangeIndex: 12 entries, 0 to 11
Data columns (total 1 columns):
data    12 non-null datetime64[ns]
dtypes: datetime64[ns](1)
Python 中的时间序列数据处理

创建时间序列:pd.DateTimeIndex

  • np.random.random
    • 随机数范围:[0,1]
    • 12 行,2 列
data = np.random.random((size=12,2))

pd.DataFrame(data=data, index=index).info()
DatetimeIndex: 12 entries, 2017-01-31 to 2017-12-31
Freq: M
Data columns (total 2 columns):
0    12 non-null float64
1    12 non-null float64
dtypes: float64(2)
Python 中的时间序列数据处理

频率别名与时间信息

ch1_1_v2 -如何在 pandas 中使用日期与时间.036.png

Python 中的时间序列数据处理

Passons à la pratique !

Python 中的时间序列数据处理

Preparing Video For Download...