如何使用python

在这里,我有一个包含时间和值的数据集。所以在这里,我想每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)

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

lawdragon 回答:如何使用python

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

我在命令行中添加了一些注释来帮助您理解这一点,同时还假设您将数据保存在DataFrame中,并且Date列设置为Date not string。否则,您可能需要在下面的循环中将字符串转换为日期。

#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)
本文链接:https://www.f2er.com/3167507.html

大家都在问