添加一个Datetime Index的小时差的列



我有一个datetimeindex的Dataframe,我需要创建一个列,其中包含以小时表示的datetimeindex的行之间的时间差。这是我的文件:

Datetime            Numbers
2020-11-27 08:30:00    1
2020-11-27 13:00:00    2
2020-11-27 15:15:00    3
2020-11-27 20:45:00    4
2020-11-28 08:45:00    5
2020-11-28 10:45:00    6
2020-12-01 04:00:00    7
2020-12-01 08:15:00    8
2020-12-01 12:45:00    9
2020-12-01 14:45:00   10
2020-12-01 17:15:00   11
...

这就是我需要的:

Datetime             Numbers   Delta
2020-11-27 08:30:00    1        Nan
2020-11-27 13:00:00    2       4.5
2020-11-27 15:15:00    3       2.25
2020-11-27 20:45:00    4       5.5
2020-11-28 08:45:00    5       12
2020-11-28 10:45:00    6       2
2020-12-01 04:00:00    7       65.25
2020-12-01 08:15:00    8       4.25
2020-12-01 12:45:00    9       4.5
2020-12-01 14:45:00   10       2
2020-12-01 17:15:00   11       2.5
...

Dataframe有数千行,所以我不能使用"for"循环。提前感谢!

编辑:我找到了一个解决方案:

df = df.reset_index()
df['Time'] = df['Datetime'].astype(np.int64) // 10**9
df['Delta'] = df['Time'].diff()/3600
df.drop(columns=['Time'],inplace =True)
df.set_index('Datetime', inplace=True)

我假设Datetime被设置为索引:

df.reset_index(inplace=True)
df['Delta'] = df['Datetime'].diff().dt.total_seconds()/3600
df.set_index('Datetime', inplace=True)

输出:

Numbers  Delta
Datetime                           
2020-11-27 08:30:00        1    NaN
2020-11-27 13:00:00        2   4.50
2020-11-27 15:15:00        3   2.25
2020-11-27 20:45:00        4   5.50
2020-11-28 08:45:00        5  12.00
2020-11-28 10:45:00        6   2.00
2020-12-01 04:00:00        7  65.25
2020-12-01 08:15:00        8   4.25
2020-12-01 12:45:00        9   4.50
2020-12-01 14:45:00       10   2.00
2020-12-01 17:15:00       11   2.50

相关内容

  • 没有找到相关文章

最新更新