以下代码运行良好:
import pandas as pd
import numpy as np
df = pd.DataFrame({'from_date': ['01-10-2003', '15-12-2004', '01-08-2012', '09-07-2001'],
'to_date': ['01-11-2003', '15-12-2006', '01-09-2012', '09-12-2001']})
df['from_date'] = pd.to_datetime(df['from_date'], format='%d-%m-%Y')
df['to_date'] = pd.to_datetime(df['to_date'], format='%d-%m-%Y')
df['Months'] = (df['to_date']-df['from_date'])/np.timedelta64(1, 'M')
df
更新包后出现如下错误:
ValueError: Unit M is not supported. Only unambiguous timedelta values durations are supported. Allowed units are 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns'
熊猫 = 2.1.4,Numpy = 1.26.2
我现在如何计算两个日期之间的月份差异?