2

I have DataFrame like below:

df = pd.DataFrame({"ID" : ["1", "2", "3"],
                   "Date" : ["12/11/2020", "12/10/2020", "05/04/2020"]})

And I need to calculate number of MONTHS from Date column until today. Below I upload result which I need:

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
dingaro
  • 2,156
  • 9
  • 29

3 Answers3

0

Try using this code that subtracts the time now with the 'Date' column, I also use np.ceil, because that rounds up a number:

df['Date'] = pd.to_datetime(df['Date'])
df['Amount'] = ((pd.to_datetime('now') - df['Date']) / np.timedelta64(1, 'M')).apply(np.ceil)
print(df)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You can modify this solution for subtract by scalar d:

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

d = pd.to_datetime('now')
df['Amount'] = 12 * (d.year - df['Date'].dt.year) + d.month - df['Date'].dt.month

print (df)
  ID       Date  Amount
0  1 2020-11-12       1
1  2 2020-10-12       2
2  3 2020-04-05       8
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0
from datetime import datetime
import pandas as pd
import numpy as np
df = pd.DataFrame({"ID" : ["1", "2", "3"],
                   "Date" : ["12/11/2020", "12/10/2020", "05/04/2020"]})
df['Month_diff'] = round(((datetime.now() - pd.to_datetime(df.Date,infer_datetime_format=True,dayfirst=True))/np.timedelta64(1, 'M'))-0.5)

This would be a one-liner where you are transforming the column Date to datetimeformat and then performing the operation. Output:

   ID   Date        Month_diff
0   1   12/11/2020  1.0
1   2   12/10/2020  2.0
2   3   05/04/2020  8.0
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53