简体   繁体   中英

Amount of months calculation in DataFrame in Python Pandas?

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:

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)

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM