I have a column called DOB which has dates formatted 31.07.1983 for example.
My data frame is named users_pd.
I want to add a column that has the current age of the customer based off the existing DOB column.
from datetime import date, timedelta
users_pd["Age"] = (date.today() - users_pd["DOB"] // timedelta(days=365.2425))
I get the error
TypeError: Invalid dtype object for __floordiv__
CodePudding user response:
Your parenthesis was incorrectly placed, and you probably failed to convert to datetime.
Use:
users_pd["Age"] = (pd.Timestamp('today')
- pd.to_datetime(users_pd["DOB"], dayfirst=True)
) // pd.Timedelta(days=365.2425)
Example:
DOB Age
0 31.07.1983 39
CodePudding user response:
Convert column to datetime and then convert timedeltas to year
s:
users_pd["DOB"] = pd.to_datetime(users_pd["DOB"], format='%d.%m.%Y')
users_pd["Age"] = (pd.to_datetime('today') - users_pd["DOB"]).astype('<m8[Y]').astype(int)