首页 > 解决方案 > 在特定时间段内的日期上添加一个小时 Pandas

问题描述

我有一个包含两列的数据框,一列是“日期”,另一列是“深度(m)”

    Date    Depth(m)

0   2015-07-09 13:00:00 2.624

1   2015-07-09 13:15:00 2.686

2   2015-07-09 13:30:00 2.747

3   2015-07-09 13:45:00 2.78

4   2015-07-09 14:00:00 2.826

5   2015-07-09 14:15:00 2.879

6   2015-07-09 14:30:00 2.938

7   2015-07-09 14:45:00 3.005

8   2015-07-09 15:00:00 3.056

9   2015-07-09 15:15:00 3.106

10  2015-07-09 15:30:00 3.173

11  2015-07-09 15:45:00 3.262

12  2015-07-09 16:00:00 3.332

13  2015-07-09 18:15:00 3.35

14  2015-07-09 18:30:00 3.324

15  2015-07-09 18:45:00 3.306

16  2015-07-09 19:00:00 3.299

我想在 2015-07-09 14:00:00 和 2015-07-09 16:00:00 之间增加一个小时

像这样输出

    Date    Depth(m)

0   2015-07-09 13:00:00 2.624

1   2015-07-09 13:15:00 2.686

2   2015-07-09 13:30:00 2.747

3   2015-07-09 13:45:00 2.78

4   2015-07-09 15:00:00 2.826

5   2015-07-09 15:15:00 2.879

6   2015-07-09 15:30:00 2.938

7   2015-07-09 15:45:00 3.005

8   2015-07-09 16:00:00 3.056

9   2015-07-09 16:15:00 3.106

10  2015-07-09 16:30:00 3.173

11  2015-07-09 16:45:00 3.262

12  2015-07-09 17:00:00 3.332

13  2015-07-09 18:15:00 3.35

14  2015-07-09 18:30:00 3.324

15  2015-07-09 18:45:00 3.306

16  2015-07-09 19:00:00 3.299

预先感谢。

标签: python

解决方案


如果尚未将Date列转换为 pandas ,并将开始和停止日期值也转换为 pandas 日期时间,然后使用并分配给定范围内的那些以小时为单位的增量。datetimenp.whereDatepd.to_timedelta

df['Date'] = pd.to_datetime(df['Date'])
start = pd.to_datetime('2015-07-09 14:00:00')
stop = pd.to_datetime('2015-07-09 16:00:00')

df['Date'] = np.where((df['Date'].ge(start))&(df['Date'].le(stop)),
                       df['Date']+pd.to_timedelta(1, 'H'),
                       df['Date'])

输出:

                  Date  Depth(m)
0  2015-07-09 13:00:00     2.624
1  2015-07-09 13:15:00     2.686
2  2015-07-09 13:30:00     2.747
3  2015-07-09 13:45:00     2.780
4  2015-07-09 15:00:00     2.826
5  2015-07-09 15:15:00     2.879
6  2015-07-09 15:30:00     2.938
7  2015-07-09 15:45:00     3.005
8  2015-07-09 16:00:00     3.056
9  2015-07-09 16:15:00     3.106
10 2015-07-09 16:30:00     3.173
11 2015-07-09 16:45:00     3.262
12 2015-07-09 17:00:00     3.332
13 2015-07-09 18:15:00     3.350
14 2015-07-09 18:30:00     3.324
15 2015-07-09 18:45:00     3.306
16 2015-07-09 19:00:00     3.299

推荐阅读