python - 获取 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)
解决方案
您可能希望重置索引并查询回索引。
print(your_dataframe.reset_index().index)
另外,要访问定位位置,您可以使用your_dataframe.iloc[position]
.
注意:请注意,如果您在过滤数据后重置索引,则索引将与过滤前不同。在进行任何过滤之前,您需要重置索引。
推荐阅读
- python - 与文件系统交互
- google-analytics - 使用数据层和 Google 跟踪代码管理器跟踪结帐行为
- node.js - Express中的路线顺序重要吗?
- java - Spring Boot 单元测试中的“java.lang.NoClassDefFoundError:无法初始化 X 类”
- mysql - mysql workbench中Info表下的表行表示什么?
- .net - 如何在 azuredevops 上自定义燃尽图
- java - 在java中以编程方式设置android复选框的属性
- fpga - 基于 CLB 的 MUX 和基于 LUT 的区别是什么
- keras - AutoKeras 1.0 - 无法导入 load_image_dataset
- python-3.x - 是否可以在不编写新文件的情况下将文本合成为语音?