您的位置:首页 > 编程语言 > Python开发

python--时间序列数据分析(学习笔记)

2020-03-15 07:18 253 查看

时间数据处理分析

一、创建时间数据

import pandas as pd
import numpy as np
from datetime import datetime
index_time = pd.date_range('20200301', periods=1000, freq='D')
#生成从20200301开始1000天的数据,作为index
data = pd.Series(range(len(index_time)), index=index_time)
#创建data
print(ser_obj.head(10))
#字符串转换为datetime
dt_str = '2017-02-18'
dt_obj = datetime.strptime(dt_str, '%Y-%m-%d')

pd.to_datetime()  #字符串转成时间格式

二、数据重采样

# 统计每个月的数据总和
resample_month_sum = data.resample('M').sum()
# 统计每个年的数据平均
resample_month_mean = data.resample('Y').mean()

1、降采样

# 统计每10天的数据和
ten_day_sum_sample = data.resample('10D').sum()
#ohlc()重采样:常常用在股票里,开盘价,最高价,l:最低价,c:收盘价
five_day_ohlc_sample = data.resample('5D').ohlc()
# 使用groupby降采样
data.groupby(lambda x: x.month).sum()
data.groupby(lambda x: x.weekday).mean()

2、升采样

df = pd.DataFrame(np.random.randn(5),index=pd.date_range('20170101', periods=5, freq='W-MON')
#freq:频率,
# 直接重采样会产生空值
print(df.resample('D').asfreq())

#ffill 空值取前面的数值
print(df.resample('D').ffill())

#bfill空值取后面的数值
print(df.resample('D').bfill())

#interpolate,根据插值算法补全数据
df.resample('D').interpolate('linear')

三、滑动窗口

df=pd.Series(np.random.randn(1000), index=pd.date_range('20170101', periods=1000))
r_obj = df.rolling(window=5)
r_obj.mean()  #查看每五日的均值
r_obj.median()
import matplotlib.pyplot as plt
%matplotlib inline

plt.figure(figsize=(15, 5))

df.plot(style='r--')
df.rolling(window=10).mean().plot(style='b')  #10日均线
df.rolling(window=20).mean().plot(style='y--')  #20日均线

  • 点赞
  • 收藏
  • 分享
  • 文章举报
song brother 发布了6 篇原创文章 · 获赞 1 · 访问量 164 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐