pandas 之 时间序列索引
import numpy as np
import pandas as pd
引入
A basic kind of time series object in pandas is a Series indexed by timestamps, which is often represented external to pandas as Python string or datetime objects:
from datetime import datetime
dates = [
datetime(2011, 1, 2),
datetime(2011, 1, 5),
datetime(2011, 1, 7),
datetime(2011, 1, 8),
datetime(2011, 1, 10),
datetime(2011, 1, 12)
]
ts = pd.Series(np.random.randn(6), index=dates)
ts
2011-01-02 0.825502
2011-01-05 0.453766
2011-01-07 0.077024
2011-01-08 -1.320742
2011-01-10 -1.109912
2011-01-12 -0.469907
dtype: float64
Under the hood, these datetime objects have been put in a DatetimeIndex:
ts.index
DatetimeIndex(['2011-01-02', '2011-01-05', '2011-01-07', '2011-01-08',
'2011-01-10', '2011-01-12'],
dtype='datetime64[ns]', freq=None)
Like other Series, arithmetic operations between differently indexed time series auto-matically align(自动对齐) on the dates:
ts + ts[::2]
2011-01-02 1.651004
2011-01-05 NaN
2011-01-07 0.154049
2011-01-08 NaN
2011-01-10 -2.219823
2011-01-12 NaN
dtype: float64
Recall that ts[::2] selects every second element in ts:
pandas stores timestamp using NumPy's datetime64 data type the nanosecond resolution:
ts.index.dtype
dtype('<M8[ns]')
Scalar values from a DatetimeIndex are Timestamp object:
stamp = ts.index[0]
stamp
Timestamp('2011-01-02 00:00:00')
A Timestamp can be substituted(被替代) anywhere you would use a datetime object. Additionally, it can store frequency information(if any) and understands how to do time zone conversions and other kinds of manipulations. More on both of these things later.
(各种转换操作, 对于时间序列)
索引-切片
Time series behaves like any other pandas.Series when you are indexing and selecting data based on label:
stamp = ts.index[2]
ts[stamp]
0.0770243257021936
As a convenience, you can also pass a string that is interpretable as a date:
ts['1/10/2011']
-1.109911691867437
ts['20110110']
-1.109911691867437
For longer time series, a year or only a year and month can be passed to easly select slices of data:
longer_ts = pd.Series(np.random.randn(1000),
index=pd.date_range('1/1/2000', periods=1000))
longer_ts[:5]
2000-01-01 0.401394
2000-01-02 0.720214
2000-01-03 0.488505
2000-01-04 0.446179
2000-01-05 -2.129299
Freq: D, dtype: float64
longer_ts['2001'][:5]
2001-01-01 0.315472
2001-01-02 0.796386
2001-01-03 0.611503
2001-01-04 0.980799
2001-01-05 0.184401
Freq: D, dtype: float64
Here, the string '2001' is interpreted as a year and selects that time period. This also works if you speicify the month:
longer_ts['2001-05'][:5]
2001-05-01 0.439009
2001-05-02 -0.304236
2001-05-03 0.603268
2001-05-04 -0.726460
2001-05-05 -0.521669
Freq: D, dtype: float64
"Slicing with detetime objects works as well"
ts[datetime(2011, 1, 7):]
'Slicing with detetime objects works as well'
2011-01-07 0.077024
2011-01-08 -1.320742
2011-01-10 -1.109912
2011-01-12 -0.469907
dtype: float64
Because most time series data is ordered chrnologically(按年代顺序的), you can slice with time-stamps not contained in a time series to perform a range query:
ts
2011-01-02 0.825502
2011-01-05 0.453766
2011-01-07 0.077024
2011-01-08 -1.320742
2011-01-10 -1.109912
2011-01-12 -0.469907
dtype: float64
ts['1/6/2011': '1/11/2011']
2011-01-07 0.077024
2011-01-08 -1.320742
2011-01-10 -1.109912
dtype: float64
As before, you can pass either a string date, datetime or timestamp. Remember that slicing in this manner produces views on the source time series like slicing NumPy arrays. This means that no data is copied and modifications on the slice will be reflected in the orginal data.
There is an equivalent instance method,truncate that slices a Series between two dates:
ts.truncate(after='1/9/2011')
2011-01-02 0.825502
2011-01-05 0.453766
2011-01-07 0.077024
2011-01-08 -1.320742
dtype: float64
All of this holds true for DataFrame as well, indexing on its rows:
# periods: 多少个, freq: 间隔
dates = pd.date_range('1/1/2000', periods=100, freq='W-WED')
long_df = pd.DataFrame(np.random.randn(100, 4),
index=dates,
columns=['Colorado', 'Texas', 'New York', 'Ohio'])
long_df.loc['5-2001']
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
| Colorado | Texas | New York | Ohio | |
|---|---|---|---|---|
| 2001-05-02 | 0.972317 | 0.407519 | 0.628906 | 1.995901 |
| 2001-05-09 | 0.299961 | -1.208505 | 1.019247 | 2.244728 |
| 2001-05-16 | 0.628163 | -0.716498 | 0.621912 | 1.257635 |
| 2001-05-23 | 0.508852 | 0.753517 | -0.793127 | 0.273496 |
| 2001-05-30 | -1.443141 | -0.878143 | -0.680227 | 0.455401 |
重复索引
- ts.is_unique
- ts.groupby(level=0)
In some applications, there may be multiple data observations falling on a particular timestamp.Here is an example:
dates = pd.DatetimeIndex(['1/1/2000', '1/2/2000',
'1/2/2000', '1/2/2000', '1/3/2000'
])
dup_ts = pd.Series(np.arange(5), index=dates)
dup_ts
2000-01-01 0
2000-01-02 1
2000-01-02 2
2000-01-02 3
2000-01-03 4
dtype: int32
We can tell that the index is not unique by checking its is_unique property:
dup_ts.index.is_unique
False
Indexing into this time series will now either produce scalar values or slice depending on whether a timestamp is duplicated:
dup_ts['1/3/2000'] # not duplicated
4
dup_ts['1/2/2000'] # duplicated
2000-01-02 1
2000-01-02 2
2000-01-02 3
dtype: int32
Suppose you wanted to aggregate the data having non-unique timestamps. One way to do this is use groupby and pass level=0
grouped = dup_ts.groupby(level=0) # 没有level 会报错, 默认是None
grouped.mean()
2000-01-01 0
2000-01-02 2
2000-01-03 4
dtype: int32
grouped.count()
2000-01-01 1
2000-01-02 3
2000-01-03 1
dtype: int64
pandas 之 时间序列索引的更多相关文章
- 笔记 | pandas之时间序列学习随笔1
1. 时间序列自动生成 ts = pd.Series(np.arange(1, 901), index=pd.date_range('2010-1-1', periods=900)) 最终生成了从20 ...
- pandas处理时间序列(2):DatetimeIndex、索引和选择、含有重复索引的时间序列、日期范围与频率和移位、时间区间和区间算术
一.时间序列基础 1. 时间戳索引DatetimeIndex 生成20个DatetimeIndex from datetime import datetime dates = pd.date_rang ...
- pandas处理时间序列(3):重采样与频率转换
五.重采样与频率转换 1. resample方法 rng = pd.date_range('1/3/2019',periods=1000,freq='D') rng 2. 降采样 (1)resampl ...
- 03. Pandas 2| 时间序列
1.时间模块:datetime datetime模块,主要掌握:datetime.date(), datetime.datetime(), datetime.timedelta() 日期解析方法:pa ...
- pandas处理时间序列(1):pd.Timestamp()、pd.Timedelta()、pd.datetime( )、 pd.Period()、pd.to_timestamp()、datetime.strftime()、pd.to_datetime( )、pd.to_period()
Pandas库是处理时间序列的利器,pandas有着强大的日期数据处理功能,可以按日期筛选数据.按日期显示数据.按日期统计数据. pandas的实际类型主要分为: timestamp(时间戳) ...
- pandas之时间序列(data_range)、重采样(resample)、重组时间序列(PeriodIndex)
1.data_range生成时间范围 a) pd.date_range(start=None, end=None, periods=None, freq='D') start和end以及freq配合能 ...
- pandas处理时间序列(4): 移动窗口函数
六.移动窗口函数 移动窗口和指数加权函数类别如↓: rolling_mean 移动窗口的均值 pandas.rolling_mean(arg, window, min_periods=None, fr ...
- pandas之时间序列
Pandas中提供了许多用来处理时间格式文本的方法,包括按不同方法生成一个时间序列,修改时间的格式,重采样等等. 按不同的方法生成时间序列 In [7]: import pandas as pd # ...
- pandas基础用法——索引
# -*- coding: utf-8 -*- # Time : 2016/11/28 15:14 # Author : XiaoDeng # version : python3.5 # Softwa ...
随机推荐
- Linux:quota磁盘配额设置
磁盘配额的概念 quota 磁盘配额功能只在指定的文件系统(分区)内有效,未设置配额的文件系统不受限制. quota 针对指定的用户账号.组账号进行限制,其他用户或组不受影响. 磁盘配额可以进行两方面 ...
- (一)JVM快速回顾总结
1,JVM内存结构(JVM体系概述,java8后的JVM) 2,GC的作用域(方法区和线程堆) 3,常见的垃圾回收算法 (1)引用计数 循环引用问题 (1) 那些对象可以作为GC_Root 虚拟机栈( ...
- c# WF 第5节 窗体的控件
本节内容: 1:控件在哪里 2:控件怎么添加 3:窗口的显示与隐藏 4:实例单击窗体,出现另一个窗体 1:控件在哪里 视图 --> 工具箱 2:控件怎么添加 第一种:从工具箱直接拉 第二种:在代 ...
- pycharm 设置django server
- LG3205/BZOJ1996 「HNOI2010」合唱队 区间DP
区间DP 区间DP: 显然是一个区间向左右拓展形成的下一个区间,具有包含关系,所以可以使用区间DP. 状态设计: 考虑和关路灯一样设计状态 因为不知道当前这个区间是从哪个区间拓展而来,即不知道这个区间 ...
- 第六章 HTTP首部
第六章 HTTP首部 HTTP首部包括:请求行<方法,URI,版本号>/响应行<版本,状态码>.请求/响应首部字段.通用首部字段.实体首部字段 1.HTTP首部字段 HTTP首 ...
- vue 多种方式控制style属性
一共用到了两种方式: 第一种:对象 第二种:数组 看代码: <!doctype html> <html lang="en"> <head> &l ...
- 58同城笔试题:数组去重;分饼干(分糖果);最小路径和(leetcode64)
1. 数组去重 题目描述 /** * 有序数组去重 * 输出最终的数字个数 * 输入:1,2,2 * 输出:2 * @author Turing * */ 代码 import java.util.*; ...
- 响应国家号召 1+X 证书 Web 前端开发考试模拟题
1+x证书Web前端开发初级理论考试样题2019 http://blog.zh66.club/index.php/archives/149/ 1+x证书Web前端开发初级实操考试样题2019 http ...
- linux不同服务器SSH连接与数据传送
linux不同服务器通过SSH连接 SCP 命令进行数据传送 1. 安装scp yum install -y openssh-client 2.命令 复制文件(本地>>远程):scp /h ...