需要使用列将新的DateTime列添加到现有数据框

时间:2019-06-06 17:34:10

标签: python pandas dataframe datetime

我有一个数据框,其中有距离和速度,我可以据此计算时间。现在,我想添加一列,在其中可以为第一行提供固定的DateTime值,它将自动添加时间并将其设置为dateTime列的下一个值

当前数据框如下:

x_coordinate    y_coordinate    z_coordinate    speed   Distance    Time1
-22                -2.28           -0.1         300     1           0.2
-21                -2.28           -0.1         300     1           0.2
-20                -2.28           -0.1         300     1           0.2
-19                -2.28           -0.1         300     1           0.2
-18                -2.28           -0.1         300     1           0.2
-17                -2.28           -0.1         300     1           0.2
-16                -2.28           -0.1         300     1           0.2
-15                -2.28           -0.1         300     1           0.2
-14                -2.28           -0.1         300     1           0.2
-13.2674           -2.601          -0.1         300 0.7998398339667759  0.15996796679335518
-13.039            -3.5743         -0.1         300 0.9997396911196436  0.1999479382239287
-12.7392           -4.5281         -0.1         300 0.9998072214182092  0.19996144428364185
-12.3697           -5.4571         -0.1         300 0.9997856020167519  0.1999571204033504

时间以秒为单位,例如0.2秒 我以300毫米/秒的速度和1毫米的距离计算。 现在,我想添加一个名为DateTime的列,该列具有第一个硬编码的Dattime值,并由类似

的时间列计算的连续值
    Datetime
    2019-02-21 03:50:39.000 --> this is hardcoded
    2019-02-21 03:50:39.200 --> this to be calculated by adding 0.2 seconds from row 1.
     and so on

1 个答案:

答案 0 :(得分:1)

尝试:

df['new_time'] = (pd.to_datetime('2019-02-21 03:50:39.000') + 
                  pd.to_timedelta(df.Time1.shift().cumsum(), unit='s')
                 )

输出(df['new_time']):

0    2019-02-21 03:50:39.000000000
1    2019-02-21 03:50:39.200000000
2    2019-02-21 03:50:39.400000000
3    2019-02-21 03:50:39.600000000
4    2019-02-21 03:50:39.800000000
5    2019-02-21 03:50:40.000000000
6    2019-02-21 03:50:40.200000000
7    2019-02-21 03:50:40.400000000
8    2019-02-21 03:50:40.600000000
9    2019-02-21 03:50:40.800000000
10   2019-02-21 03:50:40.959967967
11   2019-02-21 03:50:41.159915905
12   2019-02-21 03:50:41.359877349
Name: new_time, dtype: datetime64[ns]