Hima
Hima

Reputation: 12044

Pandas group by number of months between number of months

I have sales information for different types of parts having different durations.I want to take difference in months when my date is in 'YYYYMM' format. I have tried this.

(data.YYYYMM.max() - data.YYYYMM.min()

which gives me difference in days.how can I get this difference in months.

Upvotes: 1

Views: 37

Answers (1)

jezrael
jezrael

Reputation: 862591

You can convert column to_datetime and then to_period:

df = pd.DataFrame({'YYYYMM':['201505','201506','201508','201510']})

print (df)
   YYYYMM
0  201505
1  201506
2  201508
3  201510

df['YYYYMM'] = pd.to_datetime(df['YYYYMM'], format='%Y%m').dt.to_period('m')

a = df.YYYYMM.max() - df.YYYYMM.min()
print (a)
5

Upvotes: 1

Related Questions