首页 > 解决方案 > 如何使用python在同一列中逐行计算值直到每60分钟

问题描述

在这里,我有一个包含时间和价值的数据集。所以在这里我想每 60 分钟逐行求和值。

date	          x
8/6/2018 6:15	0
8/6/2018 6:20	2.89295
8/6/2018 6:25	2.89295
8/6/2018 6:30	2.89295
8/6/2018 6:35	2.89295
8/6/2018 6:40	2.89295
8/6/2018 6:45	2.89295
8/6/2018 6:50	2.89295
8/6/2018 6:55	2.89295
8/6/2018 7:00	2.89295
8/6/2018 7:05	2.89295
8/6/2018 7:10	2.89295
8/6/2018 7:15	2.89295
8/6/2018 7:20	2.89295
8/6/2018 7:25	2.89295
8/6/2018 7:30	2.89295
8/6/2018 7:35	2.89295
8/6/2018 7:40	2.89295
8/6/2018 7:45	3.155946
8/6/2018 7:50	3.155946
8/6/2018 7:55	3.155946
8/6/2018 8:00	3.155946
8/6/2018 8:05	3.155946
8/6/2018 8:10	3.155946
8/6/2018 8:15	3.155946

预期输出是:

在这里,我想将每五分钟的值相加,直到 60 分钟 60 分钟。

方法:

date	          x              new_x
8/6/2018 6:15	0                0
8/6/2018 6:20	2.89295          2.89295
8/6/2018 6:25	2.89295          2.89295 + 	2.89295   =   5.7859 
8/6/2018 6:30	2.89295          2.89295 + 	2.89295 + 2.89295 = 8.67885
8/6/2018 6:35	2.89295          2.89295 + 	2.89295 + 2.89295 + 2.89295 = 11.5718
8/6/2018 6:40	2.89295
8/6/2018 6:45	2.89295           like wise till to one hour 
8/6/2018 6:50	2.89295  
8/6/2018 6:55	2.89295
8/6/2018 7:00	2.89295
8/6/2018 7:05	2.89295
8/6/2018 7:10	2.89295
8/6/2018 7:15	2.89295         2.89295 + 	2.89295 + 2.89295 + 2.89295+........=   34.7154  
8/6/2018 7:20	2.89295         2.89295 (after one hour then again another hour , so
                                       then again value will be 2.89295)
                                       it will depend on the value at that time)

我不知道如何用不断增加的价值来求和。谁能帮我解决这个问题?

标签: pythontime

解决方案


我尝试使用 Pandas Grouper和 Cumulative Sum 函数查看这是否可行,但是,我找不到方法。例如,在一小时结束时有一个硬边界是可能的。如果您想在 7:00 而不是 7:15 重置总和,但不像您想要的那样。可能有人可以在这些方面提出建议。同时是一个包含大量 Python 代码的简单解决方案。

我在内嵌了一些注释来帮助您理解这一点,这也假设您将数据保存在 DataFrame 中,并且 Date 列设置为 Date 而不是字符串。否则,您可能需要在下面的循环中将字符串转换为日期。

#Get the first Date and hold its reference
lastDate = dataset.iat[0,0]
#Initialize the sum to 0
cumulativeSum = 0
for i in dataset.index:
    #Find the time difference between this row and the last held Date
    dateDiff = dataset.at[i, 'Date'] - lastDate
    if dateDiff.total_seconds() > 3600:
        #If the difference is more than 60Min then we reset the sum also hold this date as the last reference date
        cumulativeSum = 0
        lastDate = dataset.at[i, 'Date']
    #Add the current value to cumulative sum and store it in our new field
    cumulativeSum = cumulativeSum + dataset.at[i, 'Value']
    dataset.at[i, 'NewX'] = cumulativeSum
print(dataset)

推荐阅读