0

I have a tableA look like this

Transaction_Date | Name | Birth_Date
  1/01/15       | Tom  | 16/11/89 
  1/01/15       | Kate | 8/03/65 
              ....
  1/01/15       | Ken | 14/05/64 

The data type of Transaction_Date and Birth_Date is str

I want to add a age column by (Transaction_Date - Birth_Date)

my code is

tableA['Transaction_Date'] = pd.to_datetime(join_table['Transaction_Date'])
tableA['Birth_Date'] = pd.to_datetime(join_table['Birth_Date'])
tableA['Age'] = tableA['Transaction_Date'] - tableA['Birth_Date']).astype('<m8[Y]'

The outcome like below

Transaction_Date | Name | Birth_Date   | Age
 2015-01-01       | Tom  | 1989-11-16  |  25.0
 2015-01-01       | Kate | 2065-03-08  |  -50.0
              ....
 2015-01-01       | Ken  | 2064-05-14   | -49.0

the Birth_Date of Tome is correct but both Kate or Ken are wrong. It should be '1965-03-08' for Kate or '1964-05-14' for Ken

Question : how to calculate Age with int type?

When I use

int(tableA['Age'] = tableA['Transaction_Date'] - tableA['Birth_Date']).astype('<m8[Y]'
#TypeError: cannot convert the series to <class 'int'>)

Thanks in advance.

Terence Zhong
  • 181
  • 4
  • 13
  • 1
    you should avoid asking several questions. Besides, did you searched over stackoverflow first ? these are very common issues. – LoneWanderer Dec 10 '19 at 20:27
  • yes, I follow the search to get this calculation result and date convert result. And I am a bit new to python, so the result might a bit confuse for me – Terence Zhong Dec 10 '19 at 20:29
  • @LoneWanderer That's normally the case, but I actually think this is a pretty well-ordered, self-contained question that shows effort – roganjosh Dec 10 '19 at 20:31

1 Answers1

2

Try this, have to work.

df['birth_date'] = pd.to_datetime(df['Birth_Date'].str[:-2] + '19' + df['Birth_Date'].str[-2:])

To calculate AGE, you have to do the following:

df['transaction_date'] = pd.to_datetime(df['Transaction_Date'])

df['age'] = df['transaction_date'].dt.year - df['birth_date'].dt.year
Okroshiashvili
  • 3,677
  • 2
  • 26
  • 40