我在 Python Pandas 中有如下数据框:
col_date
-------
2001-01-05
1992-05-06
我想使用下面的函数来计算基于数据框中上列的年龄:
def age(born):
"""
Desc.
"""
born = datetime.strptime(born, '%y%m%d').date()
date = "2021-08-01"
return date.year - born.year - ((date.month, date.day) < (born.month, born.day))
当我检查值时,df.col_date.unique()
我得到如下结果:
array([datetime.date(2001, 1, 5), datetime.date(1992, 5, 6),dtype=object)
当我使用我的函数时:df["col_date"] = df["col_date"].apply(age)
我有错误:TypeError: strptime() argument 1 must be str, not datetime.date
但是当我将类型从字符串更改为日期时间并使用函数时,我有错误:TypeError: strptime() argument 1 must be str, not Timestamp
因为我有时间戳而不是日期时间:'2001-01-05T00:00:00.000000000'
我完全不知道我能做什么?
您可以通过pd.to_datetime()
以下方式尝试:
def age(born):
"""
Desc.
"""
born = pd.to_datetime(born,format='%Y-%m-%d')
date = pd.to_datetime("2021-08-01")
return date.year - born.year - (date.month<born.month and date.day<born.day)
#Finallly:
df["col_date"] = df["col_date"].apply(age)
或者
另一种方法是直接计算您的病情:
df['col_date']=pd.to_datetime(df['col_date'])
date = pd.to_datetime("2021-08-01")
df['col_date']=(date.year-df['col_date'].dt.year)-((df['col_date'].dt.month.lt(date.month)) & (df['col_date'].dt.day.lt(date.day)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句