Python Timedelta64 将天数转换为月数

Python Timedelta64 convert days to months

我有一个 Pandas 数据框,其中有 2 列代表开始时间戳和结束时间戳:

start       end
2016-06-13  2016-07-20

这些列的数据类型是datetime64[ns]

我现在想创建一个显示月数差异的新列:

start       end         duration
2016-06-13  2016-07-20  1.1

我尝试的是做以下事情:

df['duration'] = df['end'] - df['start']

结果如下所示:

start       end         duration
2016-06-13  2016-07-20  37 days 00:00:00.000000000

然后我尝试执行以下操作:

df['duration'] = df['end'] - df['start']).dt.months

但这会产生以下错误

AttributeError: 'TimedeltaProperties' object has no attribute 'months'

duration 列的数据类型是 timedelta64[ns]

怎样才能达到预期的效果?

import numpy as np #version: 1.16.2
import pandas as pd #version: 0.25.1

df['duration'] = (df['end'] - df['start'])/np.timedelta64(1, 'M')

以前的代码在最新版本的 numpy 中不再有效。

TypeError:无法获得 NumPy 日期时间元数据 [D] 和 [M] 的公共元数据除数,因为它们具有不兼容的非线性基本时间单位
import numpy as np #version: 1.18.5
import pandas as pd #version: 1.1.5
df['duration'] = (df['end'] - df['start']).astype('timedelta64[M]')/np.timedelta64(1, 'M')