日期时间范围索引:可能不在索引中的日期时间?

3 投票
1 回答
1632 浏览
提问于 2025-04-18 05:29

我有一个数据表,它的索引是一些时间点(datetime对象):

In <10>: all_data.head().index
Out<10>: 
Index([2014-04-23, 2014-04-13, 2014-04-15, 2014-04-30, 2014-04-06], dtype='object')

还有两个时间戳:

In <11>: d1
Out<11>: datetime.datetime(2014, 3, 24, 0, 0)

In <12>: d2
Out<12>: datetime.datetime(2014, 4, 6, 0, 0)

我想根据这个时间范围(d1:d2)来选择一列数据。需要注意的是,d1 或者 d2 可能并不在这个索引里。请问我该怎么在Pandas中做到这一点?

我试过这样做:

all_data.loc[d1:d2,:]

但是我得到了这个错误:start bound[2014-03-24 00:00:00] is not the [index]

1 个回答

3

好吧,如果你把索引设置为 DateTimeIndex,那么部分字符串索引应该就能正常工作了:

print df
print df.index

            x1  x2
date              
2014-04-23   1   2
2014-04-13   2   4
2014-04-15   3   6
2014-04-30   4   8
2014-04-06   5  10

[5 rows x 2 columns]

<class 'pandas.tseries.index.DatetimeIndex'>
[2014-04-23, ..., 2014-04-06]

这样你就可以使用部分字符串切片了:

print df['2014-03-24':'2014-04-06']

            x1  x2
2014-04-06   5  10

或者

print df.ix['2014-03-24':'2014-04-13',:]

            x1  x2
date              
2014-04-13   2   4
2014-04-06   5  10

撰写回答