取两个日期时间值或列的中位数 [英] Taking Median of two datetime values or columns
问题描述
对于下面的数据,我想取每行中前两个时间戳的中间值或中间时间,然后减去该第三个时间戳
For the below data I want to take the middle value or the middle time of the first two timestamps in each row and then subract that third timestamp
获取两个时间戳的中位数或中间时间的最佳方法是什么?
What would be the best way to take the median value or middle datime of two timestamps?
期望的输出以分钟为单位,是两个时间戳之间的差.
the output expected is in minutes the difference of two timestamps.
它是前两个时间戳的中位数或平均值减去第三个时间戳.
It is the median or mean of the first two minus the third timestamp.
它是2018-12-21 23:31:24.615
和2018-12-21 23:31:26.659
的中间值或时间戳.
it is the middle value or timestamp of 2018-12-21 23:31:24.615
and 2018-12-21 23:31:26.659
.
一旦有了该值,我想减去2018-12-21 23:31:27.975
的第三个时间戳.输出将表示分钟的值.
Once I have that value I want to subtract the third timestamp of 2018-12-21 23:31:27.975
. The output would represent a value of minutes.
推荐答案
假设df如下:
df = pd.DataFrame(data={'time1':['2018-12-21 23:31:24.615','2018-12-22 01:33:26.015'],'time2':['2018-12-21 23:31:26.659','2018-12-22 01:33:32.865'],'time3':['2018-12-21 23:31:27.975','2018-12-22 01:59:05.136']})
time1 time2 time3
0 2018-12-21 23:31:24.615 2018-12-21 23:31:26.659 2018-12-21 23:31:27.975
1 2018-12-22 01:33:26.015 2018-12-22 01:33:32.865 2018-12-22 01:59:05.136
转换"to_datetime"
Convert 'to_datetime'
df[['time1','time2','time3']] = df[['time1','time2','time3']].apply(pd.to_datetime,errors='coerce')
创建一个具有前2列平均值的列:
creating a column having the average of the first 2 columns:
my_list= []
for i in df.index:
my_list.append(pd.to_datetime((df['time1'][i].value + df['time2'][i].value)/2.0))
df['avg'] = my_list
或简单地:
df['avg'] = [(pd.to_datetime((df['time1'][i].value + df['time2'][i].value)/2.0)) for i in df.index]
第3列与平均值的区别:
finding difference of column3 and avg:
(df.time3-df.avg).astype('timedelta64[m]')
输出:
0 0.0
1 25.0
dtype: float64
P.S:您必须用数据框中的列名称替换time1
,time2
和time3
列.
P.S : you have to replace columns time1
,time2
and time3
with the column names in your dataframe.
这篇关于取两个日期时间值或列的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!