Pandas - 时间序列操作
时间序列是 Series 中常见的 dtype 类型,本节我们就来讨论 Pandas 中关于时间序列常用的操作。
Python 中处理日期时间的类型
Python API 为我们提供了 datetime.datatime 来方便地表示日期时间:
>> import datetime
>> dt = datetime.datetime(year=2021,month=9,day=26,hour=7,minute=30)
>> dt
datetime.datetime(2021, 9, 26, 7, 30)
>> print(dt)
2021-09-26 07:30:00
Pandas 中处理日期时间的类型
与 Python 类似,Pandas 使用 pandas.Timestamp 类型来表示日期时间:
>> import pandas as pd
>> ts = pd.Timestamp('2021-09-26 07:30:00')
>> ts
Timestamp('2021-09-26 07:30:00')
>> print(ts)
2021-09-26 07:30:00
>> ts.month
9
>> ts.day
26
>> ts.year
2021
Timestamp 类型还可与 pandas.Timedelta 进行日期时间运算:
>> ts + pd.Timedelta('1 days')
Timestamp('2021-09-27 07:30:00')
>> ts - pd.Timedelta('1 days')
Timestamp('2021-09-25 07:30:00')
将字符串类型转换为 Pandas 中的日期时间类型:
>> pd.to_datetime('2022-09-27')
Timestamp('2022-09-27 00:00:00')
>> pd.to_datetime('2022/09/27 12:22:39')
Timestamp('2022-09-27 00:00:00')
Pandas 中的日期时间序列
构造一个 Series :
>> s = pd.Series(['2021-09-25 07:30:00','2021-09-26 07:30:00','2021-09-27 07:30:00'])
>> s
0 2021-09-25 07:30:00
1 2021-09-26 07:30:00
2 2021-09-27 07:30:00
dtype: object
上述 Series为 object 类型,使用 pd.to_datetime 将上述 Series 转换为日期时间序列:
>> ts = pd.to_datetime(s)
>> ts
0 2021-09-25 07:30:00
1 2021-09-26 07:30:00
2 2021-09-27 07:30:00
dtype: datetime64[ns]
>> ts[0]
Timestamp('2021-09-25 07:30:00')
使用时间序列的 dt 属性可以操作日期时间的相关属性:
>> ts.dt.day
0 25
1 26
2 27
dtype: int64
>> ts.dt.weekday
0 5
1 6
2 0
dtype: int64
此外,还可以使用 pd.date_range 来构造一个按指定频率进行时间采样的 Series:
>> pd.Series(pd.date_range(start='2021-09-20',periods=7,freq='24H'))
0 2021-09-20
1 2021-09-21
2 2021-09-22
3 2021-09-23
4 2021-09-24
5 2021-09-25
6 2021-09-26
dtype: datetime64[ns]
日期时间的索引与切片
读取数据集:
>> df = pd.read_excel('../data/company.xlsx',sheet_name='数据',index_col='时间',parse_dates=True)
>> df
读取的 DataFrame 索引为时间序列:
>> df.index
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
'2020-01-05', '2020-01-06', '2020-01-07', '2020-01-08',
'2020-01-09', '2020-01-10',
...
'2020-06-17', '2020-06-18', '2020-06-19', '2020-06-22',
'2020-06-23', '2020-06-24', '2020-06-25', '2020-06-26',
'2020-06-29', '2020-06-30'],
dtype='datetime64[ns]', name='时间', length=650, freq=None)
使用 .loc 即可对时间索引进行索引和切片操作:
>> df.loc['2020-03-01':'2020-03-31']
也可是直接使用 df.loc['2020-03'] 取出三月份的数据,结果和上述结果是一致的:
>> df.loc['2020-03']
取出三月份到五月份的数据:
>> df.loc['2020-03':'2020-05']
使用布尔索引取出所有一月份的数据:
>> df[df.index.month == 1]
还可以使用 & 连接两个条件,即对两个布尔型 Series 进行与运算:取出 3 月份之后,每个月第一天的数据。
>> df[(df.index.month > 3) & (df.index.day == 1)]
日期时间的重采样
原始数据集,基本是按天进行采样的,可以使用 resample 对时间索引的 DataFrame 进行重采样。比如,按月进行重采样:
>> df.resample('M').mean()
当然,也可以两个月为周期进行重采样:
>> df.resample('2M').mean()
还可以按季度进行采样:
>> df.resample('Q').mean()
注:上述示例我们在重采样的结果上调用了
mean方法,来将采样周期内的数据计算平均值,作为新的采样结果。
绘图
对重采样获取的 DataFrame 绘制折线图:
import matplotlib.pyplot as plt
# 绘图显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
df.resample('M').mean().plot()
排序
sort_index 按索引进行排序:
>> df.sort_index()
倒序:
>> df.sort_index(ascending=False)

被折叠的 条评论
为什么被折叠?



