首页 > 解决方案 > 如何按位置选择 DatetimeIndex 的 Pandas 日期时间?

问题描述

# Example pandas Dataframe
                            temp.value  temp.period
temp.time       
2020-08-21 08:00:00+00:00   21.666667   PT1H
2020-08-21 09:00:00+00:00   21.111111   PT3H
2020-08-21 12:00:00+00:00   21.666667   PT2H

我的程序接收与上述示例类似的数据,其中温度值在 df['temp.period'] 中的可变小时数内有效。我将数据重新采样为每小时数据,如下所示:

df.resample('H').pad()

                            temp.value  temp.period
temp.time       
2020-08-21 08:00:00+00:00   21.666667   PT1H
2020-08-21 09:00:00+00:00   21.111111   PT3H
2020-08-21 10:00:00+00:00   21.111111   PT3H
2020-08-21 11:00:00+00:00   21.111111   PT3H
2020-08-21 12:00:00+00:00   21.666667   PT4H

总体问题:我需要一种重新采样最后一行的方法。在上述情况下,我需要为 13:00:00、14:00:00 和 15:00:00 添加行

当前策略:我使用正则表达式解析最后一行的 temp.period,

period = int(re.search(r'\d+(?=H)', newdf.iloc[-1]['temp.period']).group())
print(period)

4

然后希望将此小时数添加到最近一小时,以便在重新采样之前添加最后一小时的行。适合的东西:

current_latest_hour = df.iloc[-1]['temp.time']
current_latest_hour_temp = df.iloc[-1]['temp.value']
final_hour = current_latest_hour + pd.Timedelta(hours=period)
df[final_hour] = current_latest_hour_temp

# Then Resample

问题是我只是想不出办法得到current_latest_hour. 以上不起作用,因为 ['temp.time'] 是索引,而不是列。iloc 整数似乎只指列。

在整理这个问题时,我找到了一个复杂的解决方案,但觉得必须有更好的方法:我尝试先拉索引列,times = df.index但返回的是 DatetimeIndex,而不是系列,所以我不能使用 iloc。因此,在将 iloc 与time = test.to_series().iloc[-1]. 现在我有了我需要的号码,可以用time + pd.Timedelta(hours=period). 但是,在我看来,对于整体问题或这个小问题,仍然有更好的方法,而且我仍然不完全理解为什么/是否不能更轻松地从索引中选择一个值,无论是 DatetimeIndex 还是其他,所以任何建议表示赞赏。

标签: pandas

解决方案


这是一种用于.extract()将整数拉出周期并将日期保留为索引的方法。首先,创建数据框:

from io import StringIO
import pandas as pd

data = '''date                            value  period
2020-08-21 08:00:00+00:00   21.666667   PT1H
2020-08-21 09:00:00+00:00   21.111111   PT3H
2020-08-21 12:00:00+00:00   21.666667   PT2H
'''

df = pd.read_csv(StringIO(data), 
                 sep='\s\s+', 
                 engine='python', 
                 index_col='date', 
                 parse_dates=True)

# extract numeric part of period (PT1H -> 1)
df['offset'] = df['period'].str.extract(r'\w+(\d+)\w+').astype(int)

print(df)
                               value period  offset
date                                               
2020-08-21 08:00:00+00:00  21.666667   PT1H       1
2020-08-21 09:00:00+00:00  21.111111   PT3H       3
2020-08-21 12:00:00+00:00  21.666667   PT2H       2

获取最新值:

print( df['value'].iloc[-1] )
21.666667

并获取最后一个时间戳:

print( df.index[-1] )
2020-08-21 12:00:00+00:00

推荐阅读