Hes*_*ron 5 python datetime seconds pandas
目前我正在使用一个大数据框(12x47800)。十二列之一是由整数秒组成的列。我想将此列更改为由 datetime.time 格式组成的列。Schedule 是我的数据框,我尝试更改名为“depTime”的列。因为我希望它是一个 datetime.time 并且它可能会跨越午夜,所以我添加了 if 语句。这“有效”,但速度确实很慢,正如人们想象的那样。有没有更快的方法来做到这一点?我当前的代码,我唯一可以工作的是:
for i in range(len(schedule)):
t_sec = schedule.iloc[i].depTime
[t_min, t_sec] = divmod(t_sec,60)
[t_hour,t_min] = divmod(t_min,60)
if t_hour>23:
t_hour -= 23
schedule['depTime'].iloc[i] = dt.time(int(t_hour),int(t_min),int(t_sec))
Run Code Online (Sandbox Code Playgroud)
预先感谢各位。
Ps:我对Python还很陌生,所以如果有人能帮助我,我将非常感激:)
我添加了一个新的解决方案,它比原来的解决方案快得多,因为它依赖于 pandas 矢量化函数而不是循环(pandas 应用函数本质上是数据上的优化循环)。
我用和你的大小相似的样本进行了测试,差异是从 778ms 到 21.3ms。所以我绝对推荐新版本。
这两种解决方案都基于将秒整数转换为 timedelta 格式并将其添加到参考日期时间。然后,我简单地捕获结果日期时间的时间部分。
新(更快)选项:
import datetime as dt
seconds = pd.Series(np.random.rand(50)*100).astype(int) # Generating test data
start = dt.datetime(2019,1,1,0,0) # You need a reference point
datetime_series = seconds.astype('timedelta64[s]') + start
time_series = datetime_series.dt.time
time_series
Run Code Online (Sandbox Code Playgroud)
原始(较慢)答案:
这不是最优雅的解决方案,但它确实有效。
import datetime as dt
seconds = pd.Series(np.random.rand(50)*100).astype(int) # Generating test data
start = dt.datetime(2019,1,1,0,0) # You need a reference point
time_series = seconds.apply(lambda x: start + pd.Timedelta(seconds=x)).dt.time
Run Code Online (Sandbox Code Playgroud)
您应该尝试不对数据帧进行完整扫描,而应使用矢量化访问,因为它通常效率更高。
幸运的是,pandas 有一个函数可以完全满足您的要求to_timedelta:
schedule['depTime'] = pd.to_timedelta(schedule['depTime'], unit='s')
Run Code Online (Sandbox Code Playgroud)
它并不是真正的日期时间格式,但它是 pandas 的 a 等价物,datetime.timedelta并且是处理时间的便捷类型。您可以使用to_datetime,但将以接近 1970-01-01 的完整日期时间结束...
如果你确实需要datetime.time对象,你可以这样获取它们:
schedule['depTime'] = pd.to_datetime(schedule['depTime'], unit='s').dt.time
Run Code Online (Sandbox Code Playgroud)
但它们在 pandas 数据框中使用起来不太方便。
| 归档时间: |
|
| 查看次数: |
4858 次 |
| 最近记录: |