OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

subtract dates and get the result in number of months

  • Thread starter Thread starter dia05
  • Start date Start date
D

dia05

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

Code:
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')
<p>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.</p>
<pre><code>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')
</code></pre>
 

Latest posts

G
Replies
0
Views
1
Gamal Othman
G
Top