I have DataFrame like below:
JavaScript
x
3
1
df = pd.DataFrame({"ID" : ["1", "2", "3"],
2
"Date" : ["12/11/2020", "12/10/2020", "05/04/2020"]})
3
And I need to calculate number of MONTHS from Date column until today. Below I upload result which I need:
Advertisement
Answer
You can modify this solution for subtract by scalar d
:
JavaScript
1
11
11
1
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
2
3
d = pd.to_datetime('now')
4
df['Amount'] = 12 * (d.year - df['Date'].dt.year) + d.month - df['Date'].dt.month
5
6
print (df)
7
ID Date Amount
8
0 1 2020-11-12 1
9
1 2 2020-10-12 2
10
2 3 2020-04-05 8
11