python - Int/Float weighted average datetime in DataFrame -
i trying figure out way take int
or float
weighted average of datetime
fields. thinking on lines of converting datetime
int
, maths , convert datetime
. not sure how so. appreciated.
i should have been more clear here. actual problem this
>>> 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')
now trying groupby id
, take qty
weighted starttime
. please note starttime
has microsecond component well.
following not seem work, though each item of starttime
column 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__'
you can use total_seconds()
give integer can used average multiple datetime
values.
def avg_date(lst): epoch = datetime.datetime(1900, 1, 1) seconds_per_day = 3600 * 24 avg = sum((d - epoch).total_seconds() d in lst) / len(lst) return epoch + datetime.timedelta(avg // seconds_per_day, avg % seconds_per_day)
Comments
Post a Comment