[英]How to get a data element in pandas that is not in the index (but between those values)?
I have a Series of discrete states a system can be set to. 我有一系列可以设置系统的离散状态。 The setting is done at discrete time steps, eg
设置在离散的时间步骤完成,例如
import pandas as pd
states = pd.Series([1, 1, 0, 0, 1, 0, 1, 0], index=pd.date_range(
'2015-01-01', freq='2Min', periods=8))
This results in: 这导致:
2015-01-01 00:00:00 1
2015-01-01 00:02:00 1
2015-01-01 00:04:00 0
2015-01-01 00:06:00 0
2015-01-01 00:08:00 1
2015-01-01 00:10:00 0
2015-01-01 00:12:00 1
2015-01-01 00:14:00 0
Freq: 2T, dtype: int64
This means the system is in state 1 in the first four minutes, starting from minute 5 in state 0 and so on. 这意味着系统在前4分钟内处于状态1,从状态0的分钟5开始,依此类推。 Now it is necessary to answer in which state the system is at 3 minutes and 34 seconds.
现在有必要回答系统处于3分34秒的状态。 Quite obvious
states['2015-01-01 00:03:45']
won't work but raise a key error. 相当明显的
states['2015-01-01 00:03:45']
将无法工作,但会引发一个关键错误。
Is there an elegant solution to do so? 有一个优雅的解决方案吗? I assume I could do
我想我能做到
index = np.where(states.index < '2015-01-01 00:03:45')[-1][-1]
state = states.iloc[index]
to get these data but I consider this as rather ugly and I'd be happy for any suggestions for improvement. 获取这些数据,但我认为这相当丑陋,我很乐意提出任何改进建议。
Since your Series has a DatetimeIndex, you could use the asof
method : 由于您的Series具有DatetimeIndex,因此您可以使用
asof
方法 :
In [11]: states.asof('2015-01-01 00:03:45')
Out[14]: 1
In [15]: states.asof('2015-01-01 00:04:00')
Out[15]: 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.