前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Data Science | 时间序列的索引与切片

Data Science | 时间序列的索引与切片

作者头像
咸鱼学Python
发布2019-10-09 14:45:21
9530
发布2019-10-09 14:45:21
举报
时间序列的索引与切片
索引

时间序列的索引方法同样是适用于Dataframe,而且在时间序列中由于按照时间先后排序,故不用考虑顺序问题。

基本位置索引,使用的方法和列表类似:

from datetime import datetime

rng = pd.date_range('2017/1','2017/3')
ts = pd.Series(np.random.rand(len(rng)), index = rng)
print(ts.head())

print(ts[0])
print(ts[:2])
>>>
2017-01-01    0.107736
2017-01-02    0.887981
2017-01-03    0.712862
2017-01-04    0.920021
2017-01-05    0.317863
Freq: D, dtype: float64
0.107735945027
2017-01-01    0.107736
2017-01-02    0.887981
Freq: D, dtype: float64

除了基本位置索引之外还有时间序列标签索引:

from datetime import datetime

rng = pd.date_range('2017/1','2017/3')
ts = pd.Series(np.random.rand(len(rng)), index = rng)
print(ts['2017/1/2'])
print(ts['20170103'])
print(ts['1/10/2017'])
print(ts[datetime(2017,1,20)])
>>>
0.887980757812
0.712861778966
0.788336674948
0.93070380011
切片

切片的使用操作在上面索引部分的基本位置索引中有提到和Series按照index索引原理一样,也是末端包含。

rng = pd.date_range('2017/1','2017/3',freq = '12H')
ts = pd.Series(np.random.rand(len(rng)), index = rng)
print(ts['2017/1/5':'2017/1/10'])
>>>
2017-01-05 00:00:00    0.462085
2017-01-05 12:00:00    0.778637
2017-01-06 00:00:00    0.356306
2017-01-06 12:00:00    0.667964
2017-01-07 00:00:00    0.246857
2017-01-07 12:00:00    0.386956
2017-01-08 00:00:00    0.328203
2017-01-08 12:00:00    0.260853
2017-01-09 00:00:00    0.224920
2017-01-09 12:00:00    0.397457
2017-01-10 00:00:00    0.158729
2017-01-10 12:00:00    0.501266
Freq: 12H, dtype: float64


# 在这里我们可以传入月份可以直接获取整个月份的切片
print(ts['2017/2'].head())
>>>
2017-02-01 00:00:00    0.243932
2017-02-01 12:00:00    0.220830
2017-02-02 00:00:00    0.896107
2017-02-02 12:00:00    0.476584
2017-02-03 00:00:00    0.515817
Freq: 12H, dtype: float64
重复索引的时间序列
dates = pd.DatetimeIndex(['1/1/2015','1/2/2015','1/3/2015','1/4/2015','1/1/2015','1/2/2015'])
ts = pd.Series(np.random.rand(6), index = dates)
print(ts)
# 我们可以通过is_unique检查值或index是否重复
print(ts.is_unique,ts.index.is_unique)
>>>
2015-01-01    0.300286
2015-01-02    0.603865
2015-01-03    0.017949
2015-01-04    0.026621
2015-01-01    0.791441
2015-01-02    0.526622
dtype: float64
True False

按照上面的结果,可以看出在上面的时间序列中,出现了index(ts.index.is_unique)重复但值(ts.is_unique)不重复的情况。

我们可以通过时间序列把重复索引对应的值取平均值来解决索引重复的问题:

print(ts.groupby(level = 0).mean())
# 通过groupby做分组,重复的值这里用平均值处理
>>>
2015-01-01    0.545863
2015-01-02    0.565244
2015-01-03    0.017949
2015-01-04    0.026621
dtype: float64
巩固习题

1:如图创建时间序列(10*3,值为0-100的随机数),通过索引得到以下值:

① 索引得到前4行的所有值

② 索引得到2017-12-4 12:00:00的数据

③ 索引得到2017-12-4 - 2017-12-5的数据

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-12-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 咸鱼学Python 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 时间序列的索引与切片
    • 索引
      • 切片
        • 重复索引的时间序列
        • 巩固习题
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档