首页 > 解决方案 > 获取 DateTimeSeries 的整数位置索引而不是 DateTime 索引

问题描述

给定一个日期时间序列,我如何获得 int 位置?我现在可以获取日期时间索引,但我需要 int 位置索引。

示例代码

# range contains 5 rows of datetime indexed data
print(range) 

# get rows of data having value greater than 4
print(range[range.gt(4)].index)

这是打印出来的结果

Date
2020-07-21 22:00:00    6.543779
2020-07-21 22:30:00    4.095121
2020-07-21 23:00:00    4.156970
2020-07-21 23:30:00    3.819589
2020-07-22 00:00:00    4.252539
Length: 5, dtype: float64

# This returned datetime index but int position is needed
DatetimeIndex(['2020-07-21 22:00:00', '2020-07-21 22:30:00',
               '2020-07-21 23:00:00', '2020-07-22 00:00:00'],
              dtype='datetime64[ns]', name='Date', length=4, freq=None)

期待结果

# positions of data where values greater than 4
[0,1,2,4]

解决方案

快速回答,使用.reset_index()

# Use reset_index() to assign int index to the series
range = range.reset_index()

# range[0] is the column with the value you want to compare
#   .gt(4) is to get all rows with value greater than 4
#   .index is to get the index of the filter rows
print(range[range[0].gt(4)].index)

这将在结果下方打印

Int64Index([0,1,2,4], dtype='int64', length=4)

标签: pythontime-series

解决方案


您可能希望重置索引并查询回索引。

print(your_dataframe.reset_index().index)

另外,要访问定位位置,您可以使用your_dataframe.iloc[position].

注意:请注意,如果您在过滤数据后重置索引,则索引将与过滤前不同。在进行任何过滤之前,您需要重置索引。


推荐阅读