基于pandas的时间序列处理方法


import pandas as pd
import numpy as np
#生成时间序列
rng = pd.date_range('2016/1/1', periods=20, freq='D')
time = pd.Series(np.random.rand(20), index=rng)
#print(time)
#过滤数据
time.truncate(before='2016-1-10')
#print(time)

#数据重采样
'''
1.时间数据由一个频率转换至另一个频率
2.降采样
3.升采样
'''
rng = pd.date_range('1/1/2011', periods=90, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
#print(ts.head())

#转成成以月为单位
#ts.resample('M').sum()
day3Ts = ts.resample('3D').sum()
#print(ts.resample('3D').mean())


#插值填充
#print(day3Ts.resample('D').asfreq())

#三种插值方法
'''
1.ffill 空值取前面的值
2.bfill 控制取后面的值
3.interporate 线性取值
'''
#print(day3Ts.resample('D').ffill(1))#对多少个NaN填充
'''
2011-01-01   -1.376295
2011-01-02   -1.376295
2011-01-03         NaN
'''

#print(day3Ts.resample('D').bfill(1))
'''
2011-01-01    0.948138
2011-01-02         NaN
2011-01-03    0.560229
2011-01-04    0.560229
'''
#print(day3Ts.resample('D').interpolate('linear'))
'''
2011-01-01    0.453659
2011-01-02    0.993409
2011-01-03    1.533158
2011-01-04    2.072907
'''
# 滑动窗口
'''
预测时求一段时间的平均值 
'''

df = pd.Series(np.random.randn(600), index=pd.date_range('7/1/2016',freq='D', periods=600))
#print(df.head())

#r = df.rolling(window=10)#窗口大小为10

#r.max,r.median,r.std,r.skew,r.sum,r.var'
#print(r.mean())
'''
2016-07-01         NaN
2016-07-02         NaN
2016-07-03         NaN
2016-07-04         NaN
2016-07-05         NaN
2016-07-06         NaN
2016-07-07         NaN
2016-07-08         NaN
2016-07-09         NaN
2016-07-10    0.437476
2016-07-11    0.042982
'''

import matplotlib.pyplot as plt
df = pd.Series(np.random.randn(600), index=pd.date_range('7/1/2016',freq='D', periods=600))
plt.figure(figsize=(15, 5))
df.plot(style='r--')
df.rolling(window=10).mean().plot(style='b')


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值