首页 > 解决方案 > Pandas 使用 item() 从日期时间索引中给出整数

问题描述

我有 2 个数据帧,取自一个较大的帧(带有df.head(x)),两者都具有相同的索引:

print df
                     val
DT                                                                                                      
2017-03-06 00:00:00  1.06207
2017-03-06 00:02:00  1.06180
2017-03-06 00:04:00  1.06167
2017-03-06 00:06:00  1.06141
2017-03-06 00:08:00  1.06122
...                      ...
2017-03-10 21:50:00  1.06719
2017-03-10 21:52:00  1.06719
2017-03-10 21:54:00  1.06697
2017-03-10 21:56:00  1.06713
2017-03-10 21:58:00  1.06740

然后从 df 中获取 a 和 b

print a.index
print b.index

DatetimeIndex(['2017-03-06 00:32:00'], dtype='datetime64[ns]', name=u'DT', freq=None)
DatetimeIndex(['2017-03-06 00:18:00'], dtype='datetime64[ns]', name=u'DT', freq=None)

但是,当我使用 时a.index.item(),我以 1488759480000000000 的格式得到它。这意味着当我从and中获取切片df时,我得到一个空数据框ab

>>> df[a.index.item() : b.index.item()]
Empty DataFrame

此外,当我尝试将它们都转换时:

df[a.index.to_pydatetime() : b.index.to_pydatetime()]

TypeError: Cannot convert input [[datetime.datetime(2017, 3, 6, 0, 18)]] of type <type 'numpy.ndarray'> to Timestamp

这太气人了,使用时肯定应该有对象的连续性item()。谁能给我一些指示?

标签: pythonpandaspython-2.7datetimeindex

解决方案


您可以使用andloc的第一个值:ab

df.loc[a.index[0] : b.index[0]]

如果转换为,您的解决方案有效Timestamp

print (df.loc[pd.Timestamp(a.index.item()): pd.Timestamp(b.index.item())])

推荐阅读