I have a dataframe df with a field “d” which represents a date. I would like to create a “nb month” field whose values are (d of the next line) – (d of the current line). I would like the number of months as a result.
import pandas as pd
data = {'id': [1, 2, 3], 'd': ['2020-01-01', '2021-06-15', '2022-12-28']}
df = pd.DataFrame(data)
df['d'] = pd.to_datetime(df['d'])
df['d'] = df['d'].shift(-1).dt.to_period('M') - df['d'].dt.to_period('M')