这是我当前的代码
from datetime import datetime as dt
df['Age'] = datetime.datetime.now()-pd.to_datetime(df[['Day','Month','Year']])
但我的结果是
0 3380 days 10:37:40.303097
1 3512 days 10:37:40.303097
2 3131 days 10:37:40.303097
3 3739 days 10:37:40.303097
4 4550 days 10:37:40.303097
5 3204 days 10:37:40.303097
6 3813 days 10:37:40.303097
7 5819 days 10:37:40.303097
8 4532 days 10:37:40.303097
9 2444 days 10:37:40.303097
10 2664 days 10:37:40.303097
11 5527 days 10:37:40.303097
12 3706 days 10:37:40.303097
Name: Age, dtype: timedelta64[ns]
如何将以上更改为年份?
我似乎无法将Timedelta格式设置为年份-也就是说,您可以使用天的近似值-1年= 365.25天]]
df['Age'] = df['Age'].dt.days #turn timedelta into int number of days df['Age'] = df['Age']/365.25
后记,如果您的小数位数过多,可以使用Round。
这仅数天。如果您想提高精度,甚至可以在1年内使用31556952秒的秒数:
df['Seconds'] = df.Age.dt.days*24*3600+df.Age.dt.seconds #turn timedelta into int number of seconds df['Years'] = df.Seconds/31556952
基本上,您的Timedelta以许多单位表示:天,小时,分钟,秒。您想将其转换为一个单位:浮点数年。一种方法是仅转换为可用单位之一,然后转换为年。因此:
x = pd.Timedelta('3706 days 10:37:40.303097')
x.seconds
>>38260
x.days*24*3600+x.seconds
>>320236660 #Number of seconds in the Timedelta
(x.days*24*3600+x.seconds)/31556952 #Divided by the number of seconds in a year
>>10.14789577903468