python - 如何更新 pandas 数据框的日期时间索引值?

标签 python pandas

我有一小时一分钟的数据,我们在 5 分钟的时间段内重新采样:(在生产中,我们无法控制收到的数据帧。这会生成一个样本。)

import numpy as np
import pandas as pd

rng = pd.date_range('7/29/2018 17:00', periods=61, freq='min')
ts = pd.DataFrame(np.ones(len(rng)), index=rng)

five_min_bins  = ts.resample('5min').sum()

这(正确地)给出了一个从 18:00 开始的垃圾箱:

five_min_bins[-3:]
Out[]: 
                       0
2018-07-29 17:50:00  5.0
2018-07-29 17:55:00  5.0
2018-07-29 18:00:00  1.0

将最后一个数据点插入前一个数据箱的好方法是什么?

到目前为止我想出的最好的方法看起来很老套:

# hack, this question is how to improve this piece of code.
import datetime
ts = ts.reset_index(drop=False)
ts['index'].iloc[-1] = ts['index'].iloc[-1] - datetime.timedelta(milliseconds=1)
ts = ts.set_index('index')

它有效。但有人知道更优雅的解决方案吗?

ts[-1:]
Out[]: 
                     level_0    0
index                                
2018-07-29 17:59:59.999       60  1.0

ts.resample('5min').sum()[-3:]
Out[]: 
                 level_0    0
index                            
2018-07-29 17:45:00      235  5.0
2018-07-29 17:50:00      260  5.0
2018-07-29 17:55:00      345  6.0

最佳答案

类似的想法:

ts.index = ts.index[:-1].union([ts.index[-1] - pd.Timedelta(1, unit='ms')])

five_min_bins  = ts.resample('5min').sum()
print (five_min_bins)
                       0
2018-07-29 17:00:00  5.0
2018-07-29 17:05:00  5.0
2018-07-29 17:10:00  5.0
2018-07-29 17:15:00  5.0
2018-07-29 17:20:00  5.0
2018-07-29 17:25:00  5.0
2018-07-29 17:30:00  5.0
2018-07-29 17:35:00  5.0
2018-07-29 17:40:00  5.0
2018-07-29 17:45:00  5.0
2018-07-29 17:50:00  5.0
2018-07-29 17:55:00  6.0

关于python - 如何更新 pandas 数据框的日期时间索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51577437/

相关文章:

python - 传递 Pandas 数据时,Scipy linregress 返回元组

pandas - 在 Pandas 中循环列

macosX下的python : Validation: mapped file has no cdhash,完全未签名?代码必须至少经过临时签名

Python Pandas 处理 308 请求

Python - 创建索引时出现KeyError

python - 使用 list 或 numpy.array 根据条件应用 numpy.where

Python Pandas - 使用 .loc 在多列上使用 AND 和 OR 进行选择

python - 如何使用 pandas.read_csv 从列表中删除第一个元素?

python - Haystack Elasticsearch使用LTE过滤日期

python - 在线程中使用 exec(compile()) 导入问题