Python 获取DateTimeSeries的整数位置索引,而不是DateTime索引
给定一个日期时间序列,如何获取int位置?我现在可以获得datetime索引,但我需要int位置索引 示例代码 这是打印结果Python 获取DateTimeSeries的整数位置索引,而不是DateTime索引,python,time-series,Python,Time Series,给定一个日期时间序列,如何获取int位置?我现在可以获得datetime索引,但我需要int位置索引 示例代码 这是打印结果 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: floa
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)
预期结果
解决方案
快速回答,使用.reset\u 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)
您可能希望重置索引并查询回索引
print(您的数据帧.reset\u index().index)
另外,要访问位置位置,您可以使用your_dataframe.iloc[position]
注意:请注意,如果在筛选数据后重置索引,则索引将与筛选前的索引不同。在进行任何过滤之前,您需要重置索引
# 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)