当前位置: 首页 > 编程日记 > 正文

时间序列学习笔记4

6. 重采样及频率转换

重采样(resample)表示将时间序列的频率进行转换的过程。可以分为降采样和升采样等。

pandas对象都有一个resample方法,可以进行频率转换。

In [5]: rng = pd.date_range('1/1/2000', periods=100, freq='D')In [6]: ts = Series(np.random.randn(len(rng)), index=rng)
# 聚合后的值如何处理,使用mean(),默认即为mean,也可以使用sum,min等。
In [8]: ts.resample('M').mean()
Out[8]:
2000-01-31   -0.128802
2000-02-29    0.179255
2000-03-31    0.055778
2000-04-30   -0.736071
Freq: M, dtype: float64In [9]: ts.resample('M', kind='period').mean()
Out[9]:
2000-01   -0.128802
2000-02    0.179255
2000-03    0.055778
2000-04   -0.736071
Freq: M, dtype: float64

866969-20170221213712429-740044822.png

866969-20170221213724163-1954211502.png

6.1 降采样

# 12个每分钟 的采样
In [10]: rng = pd.date_range('1/1/2017', periods=12, freq='T')In [11]: ts = Series(np.arange(12), index=rng)In [12]: ts
Out[12]:
2017-01-01 00:00:00     0
2017-01-01 00:01:00     1
2017-01-01 00:02:00     2
...
2017-01-01 00:08:00     8
2017-01-01 00:09:00     9
2017-01-01 00:10:00    10
2017-01-01 00:11:00    11
Freq: T, dtype: int32# 每隔五分钟采用,并将五分钟内的值求和,赋值到新的Series中。
# 默认 [0,4),前闭后开
In [14]: ts.resample('5min').sum()  
Out[14]:
2017-01-01 00:00:00    10
2017-01-01 00:05:00    35
2017-01-01 00:10:00    21
Freq: 5T, dtype: int32# 默认 closed就是left,
In [15]: ts.resample('5min', closed='left').sum()
Out[15]:
2017-01-01 00:00:00    10
2017-01-01 00:05:00    35
2017-01-01 00:10:00    21
Freq: 5T, dtype: int32# 调整到右闭左开后,但是时间取值还是left
In [16]: ts.resample('5min', closed='right').sum()
Out[16]:
2016-12-31 23:55:00     0
2017-01-01 00:00:00    15
2017-01-01 00:05:00    40
2017-01-01 00:10:00    11
Freq: 5T, dtype: int32# 时间取值也为left,默认
In [17]: ts.resample('5min', closed='left', label='left').sum()
Out[17]:
2017-01-01 00:00:00    10
2017-01-01 00:05:00    35
2017-01-01 00:10:00    21
Freq: 5T, dtype: int32

866969-20170221213741304-1704996307.png

还可以调整offset

# 向前调整1秒
In [18]: ts.resample('5T', loffset='1s').sum()
Out[18]:
2017-01-01 00:00:01    10
2017-01-01 00:05:01    35
2017-01-01 00:10:01    21
Freq: 5T, dtype: int32

OHLC重采样

金融领域有一种ohlc重采样方式,即开盘、收盘、最大值和最小值。

In [19]: ts.resample('5min').ohlc()
Out[19]:open  high  low  close
2017-01-01 00:00:00     0     4    0      4
2017-01-01 00:05:00     5     9    5      9
2017-01-01 00:10:00    10    11   10     11

利用groupby进行重采样

In [20]: rng = pd.date_range('1/1/2017', periods=100, freq='D')In [21]: ts = Series(np.arange(100), index=rng)In [22]: ts.groupby(lambda x: x.month).mean()
Out[22]:
1    15.0
2    44.5
3    74.0
4    94.5
dtype: float64In [23]: rng[0]
Out[23]: Timestamp('2017-01-01 00:00:00', offset='D')In [24]: rng[0].month
Out[24]: 1In [25]: ts.groupby(lambda x: x.weekday).mean()
Out[25]:
0    50.0
1    47.5
2    48.5
3    49.5
4    50.5
5    51.5
6    49.0
dtype: float64

6.2 升采样和插值

低频率到高频率的时候就会有缺失值,因此需要进行插值操作。

In [26]: frame = DataFrame(np.random.randn(2,4), index=pd.date_range('1/1/2017'...: , periods=2, freq='W-WED'), columns=['Colorda','Texas','NewYork','Ohio...: '])In [27]: frame
Out[27]:Colorda     Texas   NewYork      Ohio
2017-01-04  1.666793 -0.478740 -0.544072  1.934226
2017-01-11 -0.407898  1.072648  1.079074 -2.922704In [28]: df_daily = frame.resample('D')In [30]: df_daily = frame.resample('D').mean()In [31]: df_daily
Out[31]:Colorda     Texas   NewYork      Ohio
2017-01-04  1.666793 -0.478740 -0.544072  1.934226
2017-01-05       NaN       NaN       NaN       NaN
2017-01-06       NaN       NaN       NaN       NaN
2017-01-07       NaN       NaN       NaN       NaN
2017-01-08       NaN       NaN       NaN       NaN
2017-01-09       NaN       NaN       NaN       NaN
2017-01-10       NaN       NaN       NaN       NaN
2017-01-11 -0.407898  1.072648  1.079074 -2.922704In [33]: frame.resample('D', fill_method='ffill')
C:\Users\yangfl\Anaconda3\Scripts\ipython-script.py:1: FutureWarning: fill_metho
d is deprecated to .resample()
the new syntax is .resample(...).ffill()if __name__ == '__main__':
Out[33]:Colorda     Texas   NewYork      Ohio
2017-01-04  1.666793 -0.478740 -0.544072  1.934226
2017-01-05  1.666793 -0.478740 -0.544072  1.934226
2017-01-06  1.666793 -0.478740 -0.544072  1.934226
2017-01-07  1.666793 -0.478740 -0.544072  1.934226
2017-01-08  1.666793 -0.478740 -0.544072  1.934226
2017-01-09  1.666793 -0.478740 -0.544072  1.934226
2017-01-10  1.666793 -0.478740 -0.544072  1.934226
2017-01-11 -0.407898  1.072648  1.079074 -2.922704In [34]: frame.resample('D', fill_method='ffill', limit=2)
C:\Users\yangfl\Anaconda3\Scripts\ipython-script.py:1: FutureWarning: fill_metho
d is deprecated to .resample()
the new syntax is .resample(...).ffill(limit=2)if __name__ == '__main__':
Out[34]:Colorda     Texas   NewYork      Ohio
2017-01-04  1.666793 -0.478740 -0.544072  1.934226
2017-01-05  1.666793 -0.478740 -0.544072  1.934226
2017-01-06  1.666793 -0.478740 -0.544072  1.934226
2017-01-07       NaN       NaN       NaN       NaN
2017-01-08       NaN       NaN       NaN       NaN
2017-01-09       NaN       NaN       NaN       NaN
2017-01-10       NaN       NaN       NaN       NaN
2017-01-11 -0.407898  1.072648  1.079074 -2.922704In [35]: frame.resample('W-THU', fill_method='ffill')
C:\Users\yangfl\Anaconda3\Scripts\ipython-script.py:1: FutureWarning: fill_metho
d is deprecated to .resample()
the new syntax is .resample(...).ffill()if __name__ == '__main__':
Out[35]:Colorda     Texas   NewYork      Ohio
2017-01-05  1.666793 -0.478740 -0.544072  1.934226
2017-01-12 -0.407898  1.072648  1.079074 -2.922704In [38]: frame.resample('W-THU').ffill()
Out[38]:Colorda     Texas   NewYork      Ohio
2017-01-05  1.666793 -0.478740 -0.544072  1.934226
2017-01-12 -0.407898  1.072648  1.079074 -2.922704

6.3 通过时期(period)进行重采样

# 创建一个每月随机数据,两年
In [41]: frame = DataFrame(np.random.randn(24,4), index=pd.date_range('1-2017',...: '1-2019', freq='M'), columns=['Colorda','Texas','NewYork','Ohio'])# 每年平均值进行重采样
In [42]: a_frame = frame.resample('A-DEC').mean()In [43]: a_frame
Out[43]:Colorda     Texas   NewYork      Ohio
2017-12-31 -0.441948 -0.040711  0.036633 -0.328769
2018-12-31 -0.121778  0.181043 -0.004376  0.085500# 按季度进行采用
In [45]: a_frame.resample('Q-DEC').ffill()
Out[45]:Colorda     Texas   NewYork      Ohio
2017-12-31 -0.441948 -0.040711  0.036633 -0.328769
2018-03-31 -0.441948 -0.040711  0.036633 -0.328769
2018-06-30 -0.441948 -0.040711  0.036633 -0.328769
2018-09-30 -0.441948 -0.040711  0.036633 -0.328769
2018-12-31 -0.121778  0.181043 -0.004376  0.085500In [49]: frame.resample('Q-DEC').mean()
Out[49]:Colorda     Texas   NewYork      Ohio
2017-03-31 -0.445315  0.488191 -0.543567 -0.459284
2017-06-30 -0.157438 -0.680145  0.295301 -0.118013
2017-09-30 -0.151736  0.092512  0.684201 -0.035097
2017-12-31 -1.013302 -0.063404 -0.289404 -0.702681
2018-03-31  0.157538 -0.175134 -0.548305  0.609768
2018-06-30 -0.231697 -0.094108  0.224245 -0.151958
2018-09-30 -0.614219  0.308801 -0.205952  0.154302
2018-12-31  0.201266  0.684613  0.512506 -0.270111

7. 时间序列绘图

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import Series,DataFrameframe = DataFrame(np.random.randn(20,3),index = pd.date_range('1/1/2017', periods=20, freq='M'),columns=['randn1','randn2','randn3'])
frame.plot()

866969-20170221213810116-146945057.png

8. 移动窗口函数

待续。。。

9. 性能和内存使用方面的注意事项

In [50]: rng = pd.date_range('1/1/2017', periods=10000000, freq='1s')In [51]: ts = Series(np.random.randn(len(rng)), index=rng)In [52]: %timeit ts.resample('15s').ohlc()
1 loop, best of 3: 222 ms per loopIn [53]: %timeit ts.resample('15min').ohlc()
10 loops, best of 3: 152 ms per loop

866969-20170221213823976-1706034909.png

貌似现在还有所下降。

转载于:https://www.cnblogs.com/felo/p/6426429.html

相关文章:

linux驱动编程入门实例

编辑 /*****hello.c*******/ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> MODULE_LICENSE("Dual BSD/GPL"); static int hello_init() { printk("<1>hello\n"); return 0; } static void hello…

iOS UIView快速添加事件

给UIView 做一个延展 // // UIViewSKTap.h // MeiGouYouPin // // Created by coder on 2019/10/29. // Copyright © 2019 AlexanderYeah. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN typedef void(^TapBlock)(void); interfac…

node.js中模块_在Node.js中需要模块:您需要知道的一切

node.js中模块by Samer Buna通过Samer Buna 在Node.js中需要模块&#xff1a;您需要知道的一切 (Requiring modules in Node.js: Everything you need to know) Update: This article is now part of my book “Node.js Beyond The Basics”.更新&#xff1a;这篇文章现在是我…

Sublime Text3配置Node.js开发环境

下载Nodejs插件&#xff0c;下载zip压缩包后解压链接: http://pan.baidu.com/s/1hsBk60k 密码: jrcv打开Sublime Text3&#xff0c;点击菜单“首选项&#xff08;N&#xff09;” >“浏览插件&#xff08;B&#xff09;”打开“Packages”文件夹&#xff0c;并将第1部的Node…

修改mysql的root密码

use msyql; update user set passwordpassword(新密码) where userroot; flush privileges; quitnet stop mysql #如果提示 发生系统错误5&#xff0c;就用管理员身份启动cmd.exe 转载于:https://www.cnblogs.com/walter371/p/4065904.html

iOS 开发之便捷宏定义

#define URL(A/*str*/) [NSURL URLWithString:A]// 图片 #define IMAGE(A/*str*/) [UIImage imageNamed:A]// 快速转换字符串 #define LD_STR(A/*str*/) [NSString stringWithFormat:"%ld",A] #define F2_STR(A/*str*/) [NSString stringWithFormat:"%.2f"…

rspec 测试页面元素_如何使用共享示例使您的RSpec测试干燥

rspec 测试页面元素by Parth Modi由Parth Modi 如何使用共享示例使您的RSpec测试干燥 (How to DRY out your RSpec Tests using Shared Examples) “Give me six hours to chop down a tree and I will spend the first four sharpening the axe.” — Abraham Lincoln“ 给我…

Windows搭建以太坊的私有链环境

Windows搭建以太坊的私有链环境 1、下载Geth.exe 运行文件&#xff0c;并安装https://github.com/ethereum/go-ethereum/releases/下载后&#xff0c;只有一个Geth.exe的文件2、cmd进入按章目录运行&#xff1a;geth -help看看是否可用geth命令3、在Geth安装目录下放置初始化创…

前50个斐波那契数

它有一个递推关系&#xff0c;f(1)1f(2)1f(n)f(n-1)f(n-2),其中n>23f(n)f(n2)f(n-2)-------------------------------------------- F(1) 1 F(2) 1 F(3) 2 F(4) 3 F(5) 5 F(6) 8 F(7) 13 F(8) 21 F(9) 34 F(10) 55 F(11) 89 F(12) 144 F(13) 233 F(14) 377 F(…

RAC -代替OC 中的代理

学以致用&#xff0c; 有的时候学习了很多理论 却还是忘了实践 OC 中代替代理 简洁编程 #import "ViewController.h" #import <ReactiveObjC.h> #import "SKView.h" interface ViewController ()endimplementation ViewController- (void)viewDidL…

深度学习 免费课程_深入学习深度学习,提供15项免费在线课程

深度学习 免费课程by David Venturi大卫文图里(David Venturi) 深入学习深度学习&#xff0c;提供15项免费在线课程 (Dive into Deep Learning with 15 free online courses) Every day brings new headlines for how deep learning is changing the world around us. A few e…

《音乐商店》第4集:自动生成StoreManager控制器

一、自动生成StoreManager控制器 二、查看 StoreManager 控制器的代码 现在&#xff0c;Store Manager 控制器中已经包含了一定数量的代码&#xff0c;我们从头到尾重新过一下。 1.访问数据库代码 首先&#xff0c;在控制器中包含了标准的 MVC 控制器的代码&#xff0c;为了使用…

StringUtils

/需要导入第三方jar包pinyin4j.jarimport net.sourceforge.pinyin4j.PinyinHelper;import java.util.regex.Matcher; import java.util.regex.Pattern;public class StringUtils {protected static final String TAG StringUtils.class.getSimpleName();/*** 增加空白*/public…

微信支付invalid total_fee 的报错

因为我的测试商品是0.01的 原因是微信支付的金额是不能带小数点的 直接在提交的时候 乘以 100操作 &#xff0c;因为里面设置参数的时候是 以分为单位的 [packageParams setObject: price forKey:"total_fee"]; //订单金额&#xff0c;单位为分

帧编码 场编码_去年,我帮助举办了40场编码活动。 这是我学到的。

帧编码 场编码by Florin Nitu通过弗洛林尼图 去年&#xff0c;我帮助举办了40场编码活动。 这是我学到的。 (I helped host 40 coding events last year. Here’s what I learned.) Our local freeCodeCamp study group in Brasov, Romania just held its 40th event. We even…

HDU 4540 威威猫系列故事――打地鼠(DP)

D - 威威猫系列故事――打地鼠Time Limit:100MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Status Practice HDU 4540Description 威威猫最近不务正业&#xff0c;每天沉迷于游戏“打地鼠”。 每当朋友们劝他别太着迷游戏&#xff0c;应该好好工…

iOS 在每一个cell上添加一个定时器的方案

1 首先创建一个数组&#xff0c;用来创建所有的定时器的时间 - (NSMutableArray *)totalLastTime {if (!_totalLastTime) {_totalLastTime [NSMutableArray array];}return _totalLastTime; }2 当从网络请求过来时间之后&#xff0c;循环遍历&#xff0c;行数和时间作为Key&a…

用字符串生成二维码

需要导入Zxing.jar包import android.graphics.Bitmap;import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix;public class ZxingCode {/** * 用字符串生成…

在JavaScript中重复字符串的三种方法

In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves repeating a string a certain number of times.在本文中&#xff0c;我将解释如何解决freeCodeCamp的“ 重复字符串重复字符串 ”挑战。 这涉及重…

杭电2099 整除的尾数

题目链接&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid2099 解题思路&#xff1a;将a扩大100倍之后&#xff0c;再给它从加上i(i从0到99)&#xff0c;一个一个的看哪一个能整除 反思&#xff1a;末两位是00的时候输出的是00&#xff08;这种情况题目里面的测试数据给…

iOS 验证码倒计时按钮

具体使用 [SmsTimerManager sharedManager].second (int)time; [[SmsTimerManager sharedManager] resetTime]; [SmsTimerManager sharedManager].delegate self; [strongSelf updateTime];设置代理方法 更新按钮的标题 (void)updateTime { if ([SmsTimerManager sharedMan…

树莓派centos安装的基本配置

萌新再发一帖&#xff0c;这篇文章呢主要是为大家在树莓派上安装centos以后提供一个问题的解决方案。 首先我呢觉得好奇就在某宝上花了两百来块钱买了一套树莓派&#xff0c;很多人喜欢在树莓派上安装Debian&#xff0c;我呢更青睐用Red Hat的系统&#xff0c;毕竟对Red Hat更熟…

token拦截器阻止连接_如何防止广告拦截器阻止您的分析数据

token拦截器阻止连接TL;DR Theres dataunlocker.com service coming soon (subscribe!), along with the open-sourced prototype you can use for Google Analytics or Google Tag Manager (2020 update).TL; DR即将推出dataunlocker.com服务 (订阅&#xff01;)&#xff0c;以…

使用Fiddler手机抓包https-----重要

Fiddler不仅可以对手机进行抓包&#xff0c;还可以抓取别的电脑的请求包&#xff0c;今天就想讲一讲使用Fiddler手机抓包&#xff01; 使用Fiddler手机抓包有两个条件&#xff1a; 一&#xff1a;手机连的网络或WiFi必须和电脑&#xff08;使用fiddler&#xff09;连的网络或Wi…

strtok和strtok_r

strtok和strtok_r原型&#xff1a;char *strtok(char *s, char *delim); 功能&#xff1a;分解字符串为一组字符串。s为要分解的字符串&#xff0c;delim为分隔符字符串。 说明&#xff1a;首次调用时&#xff0c;s指向要分解的字符串&#xff0c;之后再次调用要把s设成NULL。 …

iOS 标签自动布局

导入SKTagFrame SKTagFrame *frame [[SKTagFrame alloc] init];frame.tagsArray self.bigModel.Tags;// 添加标签CGFloat first_H 0;CGFloat total_H 0;for (NSInteger i 0; i< self.bigModel.Tags.count; i) {UIButton *tagsBtn [UIButton buttonWithType:UIButtonT…

引导分区 pbr 数据分析_如何在1小时内引导您的分析

引导分区 pbr 数据分析by Tim Abraham蒂姆亚伯拉罕(Tim Abraham) 如何在1小时内引导您的分析 (How to bootstrap your analytics in 1 hour) Even though most startups understand how critical data is to their success, they tend to shy away from analytics — especial…

SSL 1460——最小代价问题

Description 设有一个nm(小于100)的方格&#xff08;如图所示&#xff09;&#xff0c;在方格中去掉某些点&#xff0c;方格中的数字代表距离&#xff08;为小于100的数&#xff0c;如果为0表示去掉的点&#xff09;&#xff0c;试找出一条从A(左上角)到B&#xff08;右下角&am…

在Windows 7下面IIS7的安装和 配置ASP的正确方法

在Windows 7下如何安装IIS7&#xff0c;以及IIS7在安装过程中的一些需要注意的设置&#xff0c;以及在IIS7下配置ASP的正确方法。 一、进入Windows 7的 控制面板&#xff0c;选择左侧的打开或关闭Windows功能 。二、打开后可以看到Windows功能的界面&#xff0c;注意选择的项目…

适配iOS 13 tabbar 标题字体不显示以及返回变蓝色的为问题

// 适配iOS 13 tabbar 标题字体不显示以及返回变蓝色的为问题 if (available(iOS 13.0, *)) {//[[UITabBar appearance] setUnselectedItemTintColor:Color_666666];}