pandas时间序列

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

上述 Seriesobject 类型,使用 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辣椒种子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值