Python科学计算之Pandas 时间序列操作

时间操作

#普通的时间操作
import datetime
import pandas as pd
#设置时间
dt = datetime.datetime(year=2020,month=10,day=11,hour=13,minute=10)
dt
#输出
datetime.datetime(2020, 10, 11, 13, 10)
#打印时间
print (dt)
2020-10-11 13:10:00
  • pandas时间操作
#定义时间戳
ts = pd.Timestamp('2020-10-11')
ts
#输出
Timestamp('2020-10-11 00:00:00')
#通过ts.month ts.year等输出年月日
ts.month
10
ts.day
11

#增加天数
ts + pd.Timedelta('5 days')
#输出
Timestamp('2020-10-16 00:00:00')
#to_datetime函数
pd.to_datetime('2020-10-11')
pd.to_datetime('11/10/2020')
#输出
Timestamp('2020-11-10 00:00:00')
  • 构建一个Series字符串
s = pd.Series(['2020-10-11 00:00:00','2020-10-12 00:00:00','2020-10-13 00:00:00'])
s
#输出
0    2020-10-11 00:00:00
1    2020-10-12 00:00:00
2    2020-10-13 00:00:00
dtype: object

#转换为datetime模式
ts = pd.to_datetime(s)
ts
#输出
0   2020-10-11
1   2020-10-12
2   2020-10-13
dtype: datetime64[ns]

#显示星期(记住星期一是0以此类推)
ts.dt.weekday
#输出
0    6
1    0
2    1
dtype: int64

构建时间序列

  • 定义一个自定义时间序列
#start表示开始时间,periods表示多少行,freq表示时间间隔
pd.Series(pd.date_range(start='2020-10-11',periods = 10,freq = '6H'))
#输出
0   2020-10-11 00:00:00
1   2020-10-11 06:00:00
2   2020-10-11 12:00:00
3   2020-10-11 18:00:00
4   2020-10-12 00:00:00
5   2020-10-12 06:00:00
6   2020-10-12 12:00:00
7   2020-10-12 18:00:00
8   2020-10-13 00:00:00
9   2020-10-13 06:00:00
dtype: datetime64[ns]
  • 读取csv中数据时间序列的两种方式
#第一种
data = pd.read_csv('./data/flowdata.csv')
data['Time'] = pd.to_datatime(date['Time'])
data = data.set_index('Time')
data.head(10)
#第二种
data = pd.read_csv('./data/flowdata.csv',index_col = 0,parse_dates = True)
data.head(10)

在这里插入图片描述

  • 时间序列索引切片
data[pd.Timestamp('2012-01-01 09:00'):pd.Timestamp('2012-01-01 19:00')]
#不加Timestamp效果一样
data[('2012-01-01 09:00'):('2012-01-01 19:00')]

在这里插入图片描述

#打印2013年的数据
data['2013']

在这里插入图片描述

#打印2012年1月到2012年3月
data['2012-01':'2012-03']

在这里插入图片描述

#取出所有1月份的数据
data[data.index.month == 1]

在这里插入图片描述

#索引的布尔切片
data[(data.index.hour > 8) & (data.index.hour <12)]

在这里插入图片描述

#between_time函数
data.between_time('08:00','12:00')

在这里插入图片描述

  • 时间序列重采样
#以1天为单位求平均值(同样也可以定义最大值max())
data.resample('D').mean().head()
#以3天为单位
data.resample('3D').mean().head()

在这里插入图片描述
在这里插入图片描述

#同样我们也可以以月份、年份为单位
data.resample('M').mean().head()
data.resample('Y').mean().head()
#画个图(需要导入matplotlib)
data.resample('M').mean().plot()

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值