Lar*_*son 7 python datetime series slice pandas
我有一个由datetime.date索引的时间序列.以下是该系列的第一个结:
1999-12-31 0
2000-06-30 170382.118454
2000-12-29 -319260.443362
Run Code Online (Sandbox Code Playgroud)
我想从系列的开头到2000年12月28日切片,但这不起作用,因为那个日期不在索引中(当我尝试时我得到一个KeyError original_series[:datetime.date(2000,12,28)].我也尝试将索引转换为时间戳,但是这给出了非常虚假的结果(它制造假结,见下文),所以我想知道是否有一个很好的方法来解决这个问题.
test = pd.Series(original_series.values, map(pd.Timestamp, original_series.index))
Run Code Online (Sandbox Code Playgroud)
乍一看,这看起来没问题:
1999-12-31 0.000000
2000-06-30 170382.118454
2000-12-29 -319260.443362
Run Code Online (Sandbox Code Playgroud)
但后来我尝试做切片(2000年1月那些额外的日子来自哪里?):
In [84]: test[:'2000-12-28']
Out[84]:
1999-12-31 0.000000
2000-06-30 170382.118454
2000-01-03 -71073.979016
2000-01-04 100498.744748
2000-01-05 91104.743684
2000-01-06 82290.255459
Run Code Online (Sandbox Code Playgroud)
你可以简单地做,如果ts是你的time.serie:
In [77]: ts = pd.Series([99,65],index=pd.to_datetime(['2000-12-24','2000-12-30']))
In [78]: ts
Out[78]:
2000-12-24 99
2000-12-30 65
dtype: int64
In [79]: ts[ts.index<=pd.to_datetime('2000-12-28')]
Out[79]:
2000-12-24 99
dtype: int64
Run Code Online (Sandbox Code Playgroud)
如果你index是string刚刚入手:
ts[ts.index.map(pd.to_datetime)<=pd.to_datetime('2000-12-28')]
Run Code Online (Sandbox Code Playgroud)