在 Python Pandas DataFrame 中将 timedelta64[ns] 列转换为秒

2025-04-01 09:56:00
admin
原创
14
摘要:问题描述:pandas DataFrame 列duration包含timedelta64[ns]如下内容。如何将它们转换为秒?0 00:20:32 1 00:23:10 2 00:24:55 3 00:13:17 4 00:18:52 Name: duration, dtype: time...

问题描述:

pandas DataFrame 列duration包含timedelta64[ns]如下内容。如何将它们转换为秒?

0   00:20:32
1   00:23:10
2   00:24:55
3   00:13:17
4   00:18:52
Name: duration, dtype: timedelta64[ns]

我尝试了以下

print df[:5]['duration'] / np.timedelta64(1, 's')

但出现了错误

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    print df[0:5]['duration'] / np.timedelta64(1, 's')
  File "C:Python27libsite-packagespandascoreseries.py", line 130, in wrapper
    "addition and subtraction, but the operator [%s] was passed" % name)
TypeError: can only operate on a timedeltas for addition and subtraction, but the operator [__div__] was passed

也尝试过

print df[:5]['duration'].astype('timedelta64[s]')

但收到错误

Traceback (most recent call last):
  File "test.py", line 17, in <module>
    print df[:5]['duration'].astype('timedelta64[s]')
  File "C:Python27libsite-packagespandascoreseries.py", line 934, in astype
    values = com._astype_nansafe(self.values, dtype)
  File "C:Python27libsite-packagespandascorecommon.py", line 1653, in _astype_nansafe
    raise TypeError("cannot astype a timedelta from [%s] to [%s]" % (arr.dtype,dtype))
TypeError: cannot astype a timedelta from [timedelta64[ns]] to [timedelta64[s]]

解决方案 1:

使用Series dt 访问器来访问日期时间 (timedelta) 系列的方法和属性。

>>> s
0   -1 days +23:45:14.304000
1   -1 days +23:46:57.132000
2   -1 days +23:49:25.913000
3   -1 days +23:59:48.913000
4            00:00:00.820000
dtype: timedelta64[ns]
>>>
>>> s.dt.total_seconds()
0   -885.696
1   -782.868
2   -634.087
3    -11.087
4      0.820
dtype: float64

还有其他适用于字符串、分类和稀疏数据类型的Pandas系列访问器。

解决方案 2:

这在当前版本的 Pandas(版本 0.14)中可以正常运行:

In [132]: df[:5]['duration'] / np.timedelta64(1, 's')
Out[132]: 
0    1232
1    1390
2    1495
3     797
4    1132
Name: duration, dtype: float64

以下是针对旧版本 Pandas/NumPy 的解决方法:

In [131]: df[:5]['duration'].values.view('<i8')/10**9
Out[131]: array([1232, 1390, 1495,  797, 1132], dtype=int64)

timedelta64 和 datetime64 数据在内部存储为 8 字节整数 (dtype
'<i8')。因此,上述代码将 timedelta64s 视为 8 字节整数,然后进行整数除法以将纳秒转换为秒。

请注意,您需要 NumPy 1.7 或更新版本才能使用 datetime64/timedelta64s。

解决方案 3:

刚刚意识到这是一个老话题,无论如何,如果像我这样的流浪者只点击搜索引擎上的前 5 个结果并最终到达这里,就把它留在这里。

确保您的类型正确。

  • 如果要将日期时间转换为,只需将日期时间对象每小时、每分钟和每秒的秒数相加(如果它是在一个日期内的持续时间)。

    • 小时 - 小时 x 3600 = 秒

    • 分钟 - 分钟 x 60 = 秒

    • 秒 - 秒

linear_df['duration'].dt.hour*3600 + linear_df['duration'].dt.minute*60 + linear_df['duration'].dt.second

  • 如果您想将timedelta转换为秒,请使用下面的方法。

linear_df[:5]['duration'].astype('timedelta64[s]')

我让它像这样工作:

start_dt 和 end_dt 列采用以下格式:

import datetime

linear_df[:5]['start_dt']

0   1970-02-22 21:32:48.000
1   2016-12-30 17:47:33.216
2   2016-12-31 09:33:27.931
3   2016-12-31 09:52:53.486
4   2016-12-31 10:29:44.611
Name: start_dt, dtype: datetime64[ns]

我的持续时间采用 timedelta64[ns] 格式,即开始结束日期时间值的减法。

linear_df['duration'] = linear_df['end_dt'] - linear_df['start_dt']

结果持续时间列如下所示

linear_df[:5]['duration']

0          0 days 00:00:14
1   2 days 17:44:50.558000
2   0 days 15:37:28.418000
3   0 days 18:45:45.727000
4   0 days 19:21:27.159000
Name: duration, dtype: timedelta64[ns]

使用 pandas,我以浮点数形式记录了两个日期之间的持续时间(秒)。这样以后比较或过滤持续时间会更加容易。

linear_df[:5]['duration'].astype('timedelta64[s]')

0        14.0
1    236690.0
2     56248.0
3     67545.0
4     69687.0
Name: duration, dtype: float64

就我的情况来说,如果我想获取所有超过 1 秒的持续时间。

解决方案 4:

使用'total_seconds()'函数:

df['durationSeconds'] = df['duration'].dt.total_seconds()

解决方案 5:

嗯,答案已经过时了。这里有一个更简单的解决方案:

df.duration.dt.total_seconds()

解决方案 6:

我们可以简单地使用 pandas apply()函数

def get_seconds(time_delta):
    return time_delta.seconds

def get_microseconds(time_delta):
    return time_delta.micro_seconds

time_delta_series = df['duration']

converted_series = time_delta_series.apply(get_seconds)
print(converted_series)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2059  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1456  
  PLM(产品生命周期管理)软件在汽车行业正发挥着日益重要的作用,它贯穿于汽车从概念设计到退役处理的整个生命周期,为汽车企业提升效率、降低成本、提高产品质量提供了强大的支持。通过实际应用案例的解析,能更直观地了解PLM软件在汽车行业的价值与影响。PLM软件助力汽车设计创新在汽车设计阶段,PLM软件为设计师提供了一个协同的...
plm项目管理系统   0  
  企业数字化转型已成为当今众多企业寻求突破与发展的关键战略。在这一进程中,产品生命周期管理(PLM)系统发挥着至关重要的作用。PLM系统涵盖了从产品概念设计到产品退役的全生命周期管理,通过整合数据、流程和人员,为企业数字化转型提供了强大的支持。它不仅能提升企业内部的协同效率,还能优化产品创新流程,增强企业对市场变化的响应...
plm软件   2  
  产品生命周期管理(PLM)系统旨在整合产品从概念设计到退役的全生命周期数据与流程,助力企业提升创新能力、缩短产品上市时间、降低成本。然而,在PLM系统实施过程中,企业往往会遭遇诸多挑战。这些挑战若得不到妥善解决,将严重影响系统的实施效果与企业的业务发展。接下来,我们深入探讨PLM系统实施过程中常见的三大挑战。业务流程与...
plm系统主要干什么的   0  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用