python - 在特定时间段内的日期上添加一个小时 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
预先感谢。
解决方案
如果尚未将Date
列转换为 pandas ,并将开始和停止日期值也转换为 pandas 日期时间,然后使用并分配给定范围内的那些以小时为单位的增量。datetime
np.where
Date
pd.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
推荐阅读
- java - ByteBuddy - 创建代理,但将原始对象作为字段
- sql - SQL - 如果满足使用多个先前列的条件,则 LAG 获取先前值
- python - 多线程是在 pysimplegui 脚本中跟踪经过时间的唯一方法吗?
- angular - Angular Ionic ngIf 检查是否包含不适用于与父数组的比较
- python - python pong的__instancecheck__超过最大递归深度怎么办?
- reactjs - 它如何自动将状态对象表示为 React js 中的参数?
- spartacus-storefront - 斯巴达克斯 3 会话在注销时过期错误
- azure - Azure 逻辑应用 - 条件操作错误“提供的类型对象和对象不兼容”
- c# - C# Xamarin 清单问题
- javascript - JavaScript 对象类