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

时间序列的索引与切片
索引
时间序列的索引方法同样是适用于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

原文发布时间为:2018-12-17
本文作者: 煌金的咸鱼
本文来自云栖社区合作伙伴“ 咸鱼普拉思”,了解相关信息可以关注“
xianyuplus1995”微信公众号

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值