我正在读取存储在文件中的温度条目。 每个条目都是在温度值发生变化时生成的,因此不会定期存储。
数据示例如下:
timestamp | temperature
-----------+------------
1477400000 | 31
1477400001 | 31.5
1477400003 | 32
1477400010 | 31.5
1477400200 | 32
1477400201 | 32.5
我需要一种快速的方法来获取任何时间戳的温度,即使它不在索引中。例如,1477400002
处的温度将为 31.5
,但 1477400002
不在索引中。
为了更容易重现,可以按如下方式生成相同的数据帧:
df = pd.DataFrame(data={'temperature': [31, 31.5, 32, 31.5, 32, 32.5]},
index=[1477400000, 1477400001, 1477400003, 1477400010, 1477400200, 1477400201])
最佳答案
假设索引已经排序,可以使用np.searchsorted
返回序号位置,使用iloc
索引到df中:
In [84]:
df.iloc[max(0, np.searchsorted(df.index, 1477400002 ) -1)]
Out[84]:
temperature 31.5
Name: 1477400001, dtype: float64
在这里,我从 np.searchsorted
的结果中减去 1 以返回下限,另外为了防止返回第一个条目的情况,我还计算了 max
在 0
和返回值之间,因此如果您尝试查找 1477400000
那么这仍将返回第一个条目
关于python - 使用索引条目之间的索引值查询数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40239853/