DataFrame

时间:2016-11-10 18:26:25

标签: python datetime dataframe floating-point int

我正在尝试找出intfloat加权平均datetime字段的方法。我正在考虑将datetime转换为int,然后进行数学计算,然后转换回datetime。但不知道该怎么做。非常感谢任何帮助。

我应该在这里更清楚。实际问题是做这样的事情

>>> df1 = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11',5: '2016-10-11'}, 'Qty': {0: 100, 1: 3232, 2: 4232, 3: 4322, 4: 666, 5: 98}, 'StartTime': {0: '08:00:00.241', 1: '08:00:00.243', 2: '12:34:23.563', 3: '08:14:05.908', 4: '18:54:50.100', 5: '10:08:36.657'},'Id':{0:'abc',1:'abc',2:'bcd',3:'bcd',4:'abc',5:'bcd'}})
>>> df1
         Date   Id   Qty     StartTime
0  2016-10-11  abc   100  08:00:00.241
1  2016-10-11  abc  3232  08:00:00.243
2  2016-10-11  bcd  4232  12:34:23.563
3  2016-10-11  bcd  4322  08:14:05.908
4  2016-10-11  abc   666  18:54:50.100
5  2016-10-11  bcd    98  10:08:36.657
>>> df1['StartTime'] = pd.to_datetime(df1['Date'] + ' ' + df1['StartTime'])
>>> df1['StartTime'][0]
Timestamp('2016-10-11 08:00:00.241000')

现在我正在尝试按Id分组,并Qty加权StartTime。请注意,StartTime也包含微秒成分 即使StartTime列的每个项目都是Timestamp,以下内容似乎也不起作用:

>>> (df1.groupby['Id']).apply(lambda x:np.average(x['StartTime'], weights=x['Qty']))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'instancemethod' object has no attribute '__getitem__'

2 个答案:

答案 0 :(得分:1)

您可以使用total_seconds()为您提供一个可用于平均多个datetime值的整数。

def avg_date(lst):
    epoch = datetime.datetime(1900, 1, 1)
    seconds_per_day = 3600 * 24
    avg = sum((d - epoch).total_seconds() for d in lst) / len(lst)
    return epoch + datetime.timedelta(avg // seconds_per_day, avg % seconds_per_day)

答案 1 :(得分:0)

您可以使用时间戳

import datetime 
dt1 = datetime.datetime.now()
dt2 = datetime.datetime(1980, 1, 1)
timestamp1 = dt1.timestamp()
timestamp2 = dt2.timestamp()
timestamp_avg = (timestamp2+timestamp1)/2
dt_avg = datetime.datetime.fromtimestamp(timestamp_avg)
print(dt_avg)