Pandas Updating Weekend Date To Nearest Business Day
I have a dataframe that currently looks like this: raw_data = {'AllDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-08','2017-04-09']} import pandas as pd df = pd.DataFrame(r
Solution 1:
This works best (adding to the answer posted by Zhe):
import pandas as pd
import time
from datetime import datetime,timedelta
df = pd.DataFrame({'AllDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-08','2017-04-09']})
df['WeekDate'] = [x if x.weekday() not in [5,6] else x - timedelta(days = (x.weekday()-4)) for x in pd.to_datetime(df['AllDate'])]
Solution 2:
Try:
import pandas as pd
import time
df = pd.DataFrame({
'AllDate':['2017-04-05','2017-04-06','2017-04-07','2017-04-08','2017-04-09']
})
df['WeekDate'] = [
x if x.weekday() notin [5,6] elseNonefor x in pd.to_datetime(df['AllDate'])
]
print(df.ffill())
Solution 3:
Here's perhaps a simpler answer that comes up a lot dealing with timeseries, etc. Key is the offset objects available in Pandas tseries
df = pd.DataFrame({"AllDate": ["2017-04-01", "2017-04-02", "2017-04-03", "2017-04-04", "2017-04-09"]})
df["AllDate"] = pd.to_datetime(df["AllDate"])
df["PrevBusDate"] = df["AllDate"].apply(pd.tseries.offsets.BusinessDay().rollback)
df.head()
...
>>> AllDate PrevBusDate
0 2017-04-01 2017-03-31
1 2017-04-02 2017-03-31
2 2017-04-03 2017-04-03
3 2017-04-04 2017-04-04
4 2017-04-09 2017-04-07
NB: Don't have to convert the 'AllDate' column if you don't want to. Can simply generate the offsets and work with them however you like, eg:
[pd.tseries.offsets.BusinessDay().rollback(d) for d in pd.to_datetime(df["AllDate"])]
Post a Comment for "Pandas Updating Weekend Date To Nearest Business Day"