我有 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。这意味着当
我根据 a
和 b
从 df
中获取切片,得到一个空数据帧
>>> 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()
时对象肯定应该具有连续性。谁能给我一些指点吗?
最佳答案
您可以将 loc
与 a
和 b
的第一个值一起使用:
df.loc[a.index[0] : b.index[0]]
如果转换为时间戳
,您的解决方案将有效:
print (df.loc[pd.Timestamp(a.index.item()): pd.Timestamp(b.index.item())])
关于python - Pandas 使用 item() 从日期时间索引给出整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57124687/