Python日期时间处理问题:负时长行程下车时间修正失败
问题:修正负时长行程的下车时间
需求:为所有时长为负的行程,给dropoff_datetime列增加12小时。
按照提示要求使用带三个参数的where函数:条件对比df['duration']与timedelta(0),设置inplace=True,other参数设为dropoff_datetime列加12小时的结果,但编写的代码输出仍不正确,怀疑other语句存在问题。
原代码
# Load libraries import pandas as pd from datetime import timedelta # Loading dataset, creating duration column, and filtering to negative durations url = 'https://drive.google.com/uc?id=1YV5bKobzYxVAWyB7VlxNH6dmfP4tHBui' df = pd.read_csv(url, parse_dates = ['pickup_datetime', 'dropoff_datetime', 'dropoff_calculated']) df["duration"] = pd.to_timedelta(df["duration"]) # Task 1: add 12 hours to dropoff duration for negative durations df['duration'].where(~(df['duration'] < timedelta(0)), other = df['dropoff_datetime'] + timedelta(12), inplace = True) # Task 2: recalculate duration column df['duration'] = df['dropoff_datetime'] - df['pickup_datetime'] # Task 3: inspect first 10 rows with negative duration print(df[df['duration'] < timedelta(0)][["pickup_datetime", "dropoff_datetime", "trip_duration", "dropoff_calculated"]].head(5))
原输出结果
pickup_datetime dropoff_datetime trip_duration 34 2016-09-19 11:47:23 2016-09-19 02:21:19 0 days 02:33:56 66 2016-09-20 12:11:43 2016-09-20 02:15:55 0 days 02:04:13 74 2016-09-20 12:55:00 2016-09-20 01:03:36 0 days 00:08:36 132 2017-04-22 12:38:41 2017-04-22 01:20:13 0 days 00:41:32 231 2017-04-24 12:56:31 2017-04-24 01:06:18 0 days 00:09:47 dropoff_calculated 34 2016-09-19 14:21:19 66 2016-09-20 14:15:56 74 2016-09-20 13:03:36 132 2017-04-22 13:20:13 231 2017-04-24 13:06:18
问题根源与修正方案
核心错误
- 操作对象错误:原代码修改的是
duration列,但需求是修改dropoff_datetime列,完全偏离目标。 - 时间增量参数错误:
timedelta(12)代表12天,而非12小时,需明确指定hours=12。 - 逻辑无效:因为第一步没改对目标列,后续重新计算
duration自然还是负的。
修正后的代码
# Load libraries import pandas as pd from datetime import timedelta # Loading dataset, creating duration column url = 'https://drive.google.com/uc?id=1YV5bKobzYxVAWyB7VlxNH6dmfP4tHBui' df = pd.read_csv(url, parse_dates = ['pickup_datetime', 'dropoff_datetime', 'dropoff_calculated']) df["duration"] = pd.to_timedelta(df["duration"]) # Task 1: 为负时长的行程给dropoff_datetime加12小时 df['dropoff_datetime'].where( ~(df['duration'] < timedelta(0)), other = df['dropoff_datetime'] + timedelta(hours=12), inplace = True ) # Task 2: 重新计算duration列 df['duration'] = df['dropoff_datetime'] - df['pickup_datetime'] # Task 3: 检查修正后的负时长行(此时应无负时长数据) print(df[df['duration'] < timedelta(0)][["pickup_datetime", "dropoff_datetime", "trip_duration", "dropoff_calculated"]].head(5))
修正说明
- 修改
dropoff_datetime列后,重新计算的duration会变为正值,与输出中dropoff_calculated的预期结果一致(比如第34行的2016-09-19 14:21:19就是原下车时间加12小时后的结果)。 - 修正后执行Task3,不会再输出负时长的行,因为所有异常行程已被修正。
内容的提问来源于stack exchange,提问作者Nick Tsougy
相关产品推荐
相关产品推荐

