I have a dataframe that is indexed by dates. I'd like to shift just the dates, one business day forward (Monday-Friday), without changing the size or anything else. Is there a simple way to do this?
1 Answer
You can shift with 'B' (I think this requires numpy >= 1.7):
In [11]: rng = pd.to_datetime(['21-11-2013', '22-11-2013'])
In [12]: rng.shift(1, freq='B') # 1 business day
Out[12]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-11-22 00:00:00, 2013-11-25 00:00:00]
Length: 2, Freq: None, Timezone: None
On the Series (same on a DataFrame):
In [21]: s = pd.Series([1, 2], index=rng)
In [22]: s
Out[22]:
2013-11-21 1
2013-11-22 2
dtype: int64
In [23]: s.shift(1, freq='B')
Out[23]:
2013-11-22 1
2013-11-25 2
dtype: int64
2 Comments
user1802143
Thanks for the quick response. I know I didn't ask this in my original question, but how would you shift just 1 column along with the dates (leaving all other columns as is)?
Andy Hayden
I think you'll want to shift the column/series, and then set that to a column in the DataFrame. That is,
df[col] = df[col].shift(1, freq='B').