gpt4 book ai didi

python - 取两个日期时间值或列的中值

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:36 25 4
gpt4 key购买 nike

对于下面的数据,我想取每行中前两个时间戳的中间值或中间时间,然后减去第三个时间戳

I want to take the middle value of the first two timestamps and subract that by the third time stamp

获取两个时间戳的中值或中间日期时间的最佳方法是什么?

预期的输出是以分钟为单位的两个时间戳的差异。

它是前两个时间戳减去第三个时间戳的中位数或平均值。

它是2018-12-21 23:31:24.6152018-12-21 23:31:26.659的中间值或时间戳。

获得该值后,我想减去 2018-12-21 23:31:27.975 的第三个时间戳。输出将表示分钟值。

最佳答案

假设 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”

df[['time1','time2','time3']] = df[['time1','time2','time3']].apply(pd.to_datetime,errors='coerce')

创建一个具有前两列平均值的列:

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]

求column3和avg的差异:

(df.time3-df.avg).astype('timedelta64[m]')

输出:

0     0.0
1 25.0
dtype: float64

P.S:您必须将 time1time2time3 列替换为数据框中的列名称。

关于python - 取两个日期时间值或列的中值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53940340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com