首页 > 解决方案 > 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]

有没有更好的方法来做到这一点?

标签: pythonpandasindexingtime

解决方案


我相信你需要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]

推荐阅读