简体   繁体   English

如何获取不在索引中(但在这些值之间)的pandas中的数据元素?

[英]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.

相关问题 如何在熊猫数据框中两次隔离,然后仅在较大的熊猫数据框中修改这些值? - How isolate between two times in pandas data frame and then modify just those values in a larger pandas dataframe? 如何获得两个 pandas 索引的差异,但只有第一个索引的差异? - How to get difference of two pandas indices, but only those of the first index? Pandas - 如何用 NaN 替换这些异常值 - Pandas - How to replace those exception values with NaN 熊猫:获取每个元素的索引 - Pandas: get index of each element 如何在pandas数据框中获取行,在列中使用最大值并保留原始索引? - How to get rows in pandas data frame, with maximal values in a column and keep the original index? 如何使用Pandas在CSV文件中创建新列,并根据这些列中的值添加数据 - How do I create a new column in a csv file using Pandas, and add data depending on the values in those columns 如何获取仅在熊猫中出现超过X时间的值的虚拟变量 - How to get dummies of only those values that occur more than X time in Pandas 如何从 pandas 数据框中删除下午 6:00 到上午 9:00 之间的日期时间索引值? - How can I remove a datetime index values from a pandas data frame that are in between 6:00 p.m. and 9:00 a.m.? 如何使用Pandas通过索引获取两个csv之间的差异 - How to get the difference between two csv by Index using Pandas 使用熊猫如何逐步增加值并取这些值的总和 - Using Pandas how to multiply the values incrementally and take the summation of those values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM