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

原文地址:https://www.cnblogs.com/chenjieyouge/p/12046377.html

时间: 2024-07-31 10:18:39

pandas 之 时间序列索引的相关文章

十分钟入门pandas数据结构和索引

pandas数据结构和索引是入门pandas必学的内容,这里就详细给大家讲解一下,看完本篇文章,相信你对pandas数据结构和索引会有一个清晰的认识. 一.数据结构介绍 在pandas中有两类非常重要的数据结构,即序列Series和数据框DataFrame.Series类似于numpy中的一维数组,除了通吃一维数组可用的函数或方法,而且其可通过索引标签的方式获取数据,还具有索引的自动对齐功能:DataFrame类似于numpy中的二维数组,同样可以通用numpy数组的函数和方法,而且还具有其他灵

《利用Python进行数据分析》之pandas的时间序列基础

本章以<利用python进行数据分析>的第10章:时间序列 为基础,整理了pandas 库中时间序列相关用法. 时间序列数据的意义取决于具体的应用场景,主要有以下几种: 时间戳(timestamp) 固定时期(period) 时间间隔(interval) 实验或过程时间 pandas提供了一组标准的时间序列处理工具和算法,可以轻松的对时间序列进行切片.聚合,对定期/不定期的时间序列进行重采样等. 这些工具大部分对金融和经济数据尤为有用,同时也可以用来分析服务器和日志数据. 1.日期和时间数据类

Pandas Cookbook -- 06索引对齐

索引对齐 简书大神SeanCheney的译作,我作了些格式调整和文章目录结构的变化,更适合自己阅读,以后翻阅是更加方便自己查找吧 import pandas as pd import numpy as np 1 索引方法 college = pd.read_csv('data/college.csv') college.iloc[:5,:5] .dataframe tbody tr th:only-of-type { vertical-align: middle } .dataframe tbo

Pandas | 08 重建索引

重新索引会更改DataFrame的行标签和列标签. 可以通过索引来实现多个操作: 重新排序现有数据以匹配一组新的标签. 在没有标签数据的标签位置插入缺失值(NA)标记. import pandas as pd import numpy as np N=20 df = pd.DataFrame({ 'A': pd.date_range(start='2016-01-01',periods=N,freq='D'), 'x': np.linspace(0,stop=N-1,num=N), 'y': n

pandas基础--层次化索引

以下代码的前提:import pandas as pd 层次化索引使你能在一个轴上拥有多个(两个以上)索引级别.抽象的说,它使你能以低维度形式处理高维度数据. 1 >>> data = pd.Series(np.random.randn(10), index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'], [1, 2, 3, 1, 2, 3, 1, 2, 2, 3]]) 2 >>> data 3 a 1 3.23

利用Python进行数据分析(11) pandas基础: 层次化索引

层次化索引 层次化索引指你能在一个数组上拥有多个索引,例如: 有点像Excel里的合并单元格对么? 根据索引选择数据子集 以外层索引的方式选择数据子集: 以内层索引的方式选择数据: 多重索引Series转换为DataFrame 层次化索引在数据重塑和分组中扮演着很重要的角色,例如,上面的层次化索引数据可以转换为一个DataFrame: 对于一个DataFrame,横轴和竖轴都可以有层次化索引,例如: 重排分级顺序 根据索引交换 swaplevel()函数可以将两个级别的数据进行交换,例如: 根据

Pandas系列(六)-时间序列详解

内容目录 1. 基础概述 2. 转换时间戳 3. 生成时间戳范围 4. DatetimeIndex 5. DateOffset对象 6. 与时间序列相关的方法 6.1 移动 6.2 频率转换 6.3 重采样 在处理时间序列的的过程中,我们经常会去做以下一些任务: 生成固定频率日期和时间跨度的序列 将时间序列整合或转换为特定频率 基于各种非标准时间增量(例如,在一年的最后一个工作日之前的5个工作日)计算“相对”日期,或向前或向后“滚动”日期 使用 Pandas 可以轻松完成以上任务. 一.基础概述

Python——Pandas 时间序列数据处理

介绍 Pandas 是非常著名的开源数据处理库,我们可以通过它完成对数据集进行快速读取.转换.过滤.分析等一系列操作.同样,Pandas 已经被证明为是非常强大的用于处理时间序列数据的工具.本节将介绍所有 Pandas 在时间序列数据上的处理方法. 知识点 创建时间对象 时间索引对象 时间算术方法 创建时间对象 在 Pandas 中关于时间序列的常见对象有 6 种,分别是 Timestamp(时间戳).DatetimeIndex(时间戳索引).Period(时间段).PeriodIndex(时间

pandas中Series对象和DataFrame对象的索引

1.Series obj = pd.Series(range(5),index=['a','a','b','b','c']) #pandas支持重复索引 可以直接用Series['索引名']:obj['a'] 也可以使用obj.a loc和iloc同样适用 2.DataFrame frame = pd.DataFrame(np.arange(12).reshape(3,4),index=['one','two','three'],columns=['a','b','c','d') 使用DataF