gpt4 book ai didi

python - 如何从开始时间中减去每次

转载 作者:行者123 更新时间:2023-12-02 02:37:17 24 4
gpt4 key购买 nike

我有一个数据框“user1”,大约有 100000 行,其中一些条目如下:

    user                    timestamp        x          y          z       class   
0 0x11 2018-04-10 12:37:51.252 -0.86 6.51 1.28 walk
1 0x11 2018-04-10 12:37:51.252 -3.16 9.52 2.98 walk
2 0x11 2018-04-10 12:37:51.324 -3.31 8.94 2.24 walk

我想要当前时间和开始时间之间的差值,而不是完整时间,即假设第三行中的时间戳是2018-04-10 12:37:51.252。我想将其更改为 (2018-04-10 12:37:51.252 - 2018-04-10 12:37:51.324 = 0.72 秒)。如何用 Pandas 做到这一点。所有其他列条目应保持原样。

最佳答案

第一步是确保您的日期时间列是日期时间,

import numpy as np 
import pandas as pd
df['timestamp'] = pd.to_datetime(df['timestamp'])

接下来,我们使用 transform 获取每个用户最早的时间戳记录

transform的好处是可以在不修改索引的情况下使用groupby方法,非常方便。

ts = df.groupby(['user'])['timestamp'].transform('min')

然后以秒为单位返回增量以匹配您的目标输出。

df['timedelta'] = (df['timestamp'] - ts) / np.timedelta64(1,'s')

print(df)

user timestamp x y z class timedelta
0 0x11 2018-04-10 12:37:51.252 -0.86 6.51 1.28 walk 0.000
1 0x11 2018-04-10 12:37:51.252 -3.16 9.52 2.98 walk 0.000
2 0x11 2018-04-10 12:37:51.324 -3.31 8.94 2.24 walk 0.072

关于python - 如何从开始时间中减去每次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64118057/

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