python - 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
时,我得到一个空数据框a
b
>>> 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()
。谁能给我一些指示?
解决方案
您可以使用andloc
的第一个值:a
b
df.loc[a.index[0] : b.index[0]]
如果转换为,您的解决方案有效Timestamp
:
print (df.loc[pd.Timestamp(a.index.item()): pd.Timestamp(b.index.item())])
推荐阅读
- tensorflow - 有效地将成对样本存储为 TFRecords
- visual-studio-code - VSCode中自定义树视图中多个选定项目的上下文菜单
- python - 获取用户输入关键字并在 Windows Shell 中使用 Os 模块运行它
- laravel - 如何在 laravel 的键值对中获取验证器失败响应
- jquery - 在grapesjs样式管理器中集成select2或任何自定义选择插件
- powershell - 如何使用powershell查找和替换.csproj中的文本
- javascript - 打字稿错误:类型“[字符串,未知] []”上不存在属性“平面”
- c# - 如何打破循环并排除 C# 中的最后一个输入?
- sass - SASS (gulp-sass) 语法问题 - 带有变量的 @media 没有输出
- javascript - 在表格中布置子元素的最佳方式