一列有日期,但另一列有一个包含日期的字符串,所以我首先需要从该字符串中提取日期部分.
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
# the dataframe - id column always starts with year, month and day
df = pd.DataFrame({'id': ['19520630F8', '19680321A5', '19711113E2'],
'dte': ['2010-06-02', '2007-08-12', '2013-01-23']})
# create a date string from df['id'] to the format yyyy-mm-dd
dob = (df['id'].str[:4] + '-' +
df['id'].str[4:6] + '-' +
df['id'].str[6:8])
# calculate age (years only) at df['dte']
df['age'] = relativedelta(date, dob).years
我收到错误消息:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我不明白我的数据的模糊性,以及应用那些空/ bool / item的位置……
df [‘dta’]列,如果是对象数据类型而不是datetime,但在pd.to_datetime中包装dob的创建不会有帮助.
编辑
预期的产出应该是
dte id age
0 2010-06-02 19520630F8 57
1 2007-08-12 19680321A5 39
2 2013-01-23 19711113E2 41
解决方法:
我相信需要:
df['age'] = (np.floor((pd.to_datetime(df['dte']) -
pd.to_datetime(dob)).dt.days / 365.25)).astype(int)
print (df)
id dte age
0 19520630F8 2010-06-02 57
1 19680321A5 2007-08-12 39
2 19711113E2 2013-01-23 41
细节:
将列转换为日期时间并减去:
print (pd.to_datetime(df['dte']) - pd.to_datetime(dob))
0 21156 days
1 14388 days
2 15047 days
dtype: timedelta64[ns]
转换为天,然后转换为年:
print ((pd.to_datetime(df['dte']) - pd.to_datetime(dob)).dt.days / 365.25)
0 57.921971
1 39.392197
2 41.196441
dtype: float64
最后一层的价值为numpy.floor.
:
print ((np.floor((pd.to_datetime(df['dte']) - pd.to_datetime(dob)).dt.days / 365.25)))
0 57.0
1 39.0
2 41.0
dtype: float64