Pandas 使用 item() 从日期时间索引给出整数
Pandas gives integer from datetime index with 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
a 和 b 然后取自 df
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]]
如果转换为 Timestamp
,您的解决方案有效:
print (df.loc[pd.Timestamp(a.index.item()): pd.Timestamp(b.index.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
a 和 b 然后取自 df
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]]
如果转换为 Timestamp
,您的解决方案有效:
print (df.loc[pd.Timestamp(a.index.item()): pd.Timestamp(b.index.item())])