[英]Getting values from time indexed pandas dataframe for a specific time within the two timestamps
I have the following pandas dataframe df:我有以下熊猫数据框 df:
C1 C2 C3
Date
2000-01-01 00:00:00 2 175 160
2000-01-01 01:00:00 4 192 164
2000-01-01 02:00:00 6 210 189
2000-01-01 03:00:00 8 217 199
2000-01-01 04:00:00 10 176 158
from which I need to get the value of C1, C2 and C3 for a specific datetime:我需要从中获取特定日期时间的 C1、C2 和 C3 的值:
import datetime
my_specific_time = str(datetime.datetime(2000, 1, 1, 1, 0, 0))
print(df['C1'].loc[mytime]) # prints 4
The problem is that I can only get values for the dates stored in the df.问题是我只能获取存储在 df 中的日期的值。 For example, getting the value of
C1
for time 2000-01-01 01:30:00
is not possible unless I resample my dataframe:例如,除非我重新采样数据帧,否则无法获取时间
2000-01-01 01:30:00
的C1
值:
upsampled = df.resample('30min').ffill()
my_specific_time = str(datetime.datetime(2000, 1, 1, 1, 30, 0))
print(upsampled['C1'].loc[mytime]) # again prints 4
Please note that all the value of C1
between timespan of 2000-01-01 01:00:00
and 2000-01-01 02:00:00
is 4
.请注意,所有值
C1
的时间跨度之间2000-01-01 01:00:00
和2000-01-01 02:00:00
是4
。 Now the problem is that my_specific_time
can be any random time and I would need to resample df using small enough values to be able to get the value for.现在的问题是
my_specific_time
可以是任何随机时间,我需要使用足够小的值重新采样 df 以便能够获得值。 I think this is not the best solution for this problem.我认为这不是这个问题的最佳解决方案。
While looking for possible solutions I only came across time spans in pandas but I did not quite understand how possibly I can use it in my problem.在寻找可能的解决方案时,我只遇到了 Pandas 的时间跨度,但我不太明白我有多大可能在我的问题中使用它。
Use DataFrame.asof
method:使用
DataFrame.asof
方法:
print(df['C1'].asof(my_specific_time))
4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.