Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get the difference of Pandas DatetimeIndex series in days?

Say I have a series of pandas.tseries.index.DatetimeIndex, which is basically weekdays of 2016. Is there any easy/elegant way of finding out the sequential difference in days of the series? Just like .diff() does for an integer or float DataFrame column.

import pandas as pd
import numpy as np
ds = pd.date_range("2016-01-01","2016-12-31",freq='B')

# I was hoping for something like this:
ds.diff().days

# this gives me what I want, but it is ugly and unintuitive
np.diff(ds) / 86400000000000

I also thought about np.diff(ds.date) but it gives me an ndarray of datetime.timedelta, and i don't know how to transform it into an integer array/series without a for-loop.

like image 769
cxwf Avatar asked Oct 15 '25 17:10

cxwf


1 Answers

try this:

In [154]: ds.to_series().diff()
Out[154]:
2016-01-01      NaT
2016-01-04   3 days
2016-01-05   1 days
2016-01-06   1 days
2016-01-07   1 days
2016-01-08   1 days
2016-01-11   3 days
2016-01-12   1 days
2016-01-13   1 days
2016-01-14   1 days
2016-01-15   1 days
2016-01-18   3 days
2016-01-19   1 days
2016-01-20   1 days
2016-01-21   1 days
2016-01-22   1 days
2016-01-25   3 days
2016-01-26   1 days
2016-01-27   1 days
2016-01-28   1 days
2016-01-29   1 days
2016-02-01   3 days
2016-02-02   1 days
2016-02-03   1 days
2016-02-04   1 days
              ...
like image 154
MaxU - stop WAR against UA Avatar answered Oct 18 '25 06:10

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!