python - Pandas 将时间范围转换为索引
问题描述
您能否建议我一种将时间段转换为相应索引的简单方法?
我有一个函数可以根据我无法更改的数字索引(从第 10 行到第 20 行)从数据框中选择条目。同时,我的数据框有时间索引,我根据时间戳选择了其中的一部分。如何将这些时间戳转换为相应的数字索引?
非常感谢亚历克斯
添加一些示例:
small_df.index[1]
Out[894]: Timestamp('2019-02-08 07:53:33.360000')
small_df.index[10]
Out[895]: Timestamp('2019-02-08 07:54:00.149000') # instead of time stamps.
这些是我想从具有时间索引的第二个数据帧中选择的时间段。但我想用数字索引来做到这一点这意味着 1. 找出哪些数字索引对应于上面的时间段
根据上面的评论,这可能与我需要的非常接近:
start=second_dataframe.index.get_loc(pd.Timestamp(small_df.index[1]))
end=second_dataframe.index.get_loc(pd.Timestamp(small_df.index[10]))
picked_rows= second_dataframe[start:end]
有没有更好的方法来做到这一点?
解决方案
我相信你需要Index.get_loc
如果需要位置:
small_df.index.get_loc(pd.Timestamp('2019-02-08 07:53:33.360000'))
1
编辑:如果值始终匹配,则可以先获取时间戳形式并通过以下方式提取第二行DataFrame.loc
:
start = small_df.index[1]
end = small_df.index[10]
picked_rows = second_dataframe.loc[start:end]
或L
start=pd.Timestamp(small_df.index[1])
end=pd.Timestamp(small_df.index[10])
picked_rows = second_dataframe.loc[start:end]
推荐阅读
- r - 运行线性回归模型方程的 REML 代码错误
- php - 在 PHP 中,我想在我的数据库日期列(时间戳类型)中按日期过滤我的数据
- acumatica - 如何在表单文本控件中启用超链接?
- swift - 将坐标(来自 UIViewController)添加到常量文件
- php - CodeIgniter 获取登录用户的会话数据
- php - 如何在php中重命名和保存文件
- python - 我正在尝试使用 openCV 和 python 构建运动检测器,但是当我终止程序时显示窗口没有响应
- azure-devops - 如何从 Azure DevOps 导出报告
- javascript - this.setState() 在 this.setState() 的回调中
- c - 制作并应用 apue.h