Python:在数据帧上转换时间单位

问题描述 投票:0回答:1

人。我在DataFrame的两个Datetime列之间进行了算术运算,产生了以下结果:

28 days 15:16:53
7 days 13:12:31
334 days 01:04:46.123501
376 days 09:45:21.546136
-1 days +23:56:21.954750
-1 days +23:59:40.110747

[当我尝试将其放入一个numpy数组时,它变成了纳秒:

array([ 2474213000000000,   652351000000000, 28861486123501000, ...,
       -218045250000,      -19889253000,   673953486963000],
  dtype='timedelta64[ns]')

并且当我尝试使用此数组绘制直方图时,出现以下错误:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

我需要将其转换为更易于管理的时间单位,以便可以先创建数组,然后再绘制直方图。谢谢!

python numpy datetime timedelta
1个回答
0
投票

假设您有一系列Timedelta(我们称它为delta

0           28 days 15:16:53
1            7 days 13:12:31
2   334 days 01:04:46.123501
3   376 days 09:45:21.546136
4   -1 days +23:56:21.954750
5   -1 days +23:59:40.110747
dtype: timedelta64[ns]

您可以轻松地将其转换为一系列的浮点数:

delta.astype('int64')/(24*60*60*1000000000)

给予:

0     28.636725
1      7.550359
2    334.044978
3    376.406499
4     -0.002524
5     -0.000230
dtype: float64

只需删除24*以具有浮点小时,相同的分钟或秒

© www.soinside.com 2019 - 2024. All rights reserved.