I have a little problem with the .loc
function.
Here is the code:
date = df.loc [df ['date'] == d] .index [0]
d
is a specific date (e.g. 21.11.2019)
The problem is that the weekend can take days. In the dataframe in the column date
there are no values for weekend days. (contains calendar days for working days only)
Is there any way that if d
is on the weekend he'll take the next day?
I would have something like index.get_loc
, method = bfill
Does anyone know how to implement that for .loc
?
IIUC you want to move dates of format: dd.mm.yyyy
to nearest Monday, if they happen to fall during the weekend, or leave them as they are, in case they are workdays. The most efficient approach will be to just modify d
before you pass it to pandas.loc[...]
instead of looking for the nearest neighbour.
What I mean is:
import datetime
d="22.12.2019"
dt=datetime.datetime.strptime(d, "%d.%m.%Y")
if(dt.weekday() in [5,6]):
dt=dt+datetime.timedelta(days=7-dt.weekday())
d=dt.strftime("%d.%m.%Y")
Output:
23.12.2019
Edit
In order to just take first date, after or on d
, which has entry in your dataframe try:
import datetime
df['date']=pd.to_datetime(df['date'], format='%d.%m.%Y')
dt=datetime.datetime.strptime(d, "%d.%m.%Y")
d=df.loc[df ['date'] >= d, 'date'].min()
dr.loc[df['date']==d]...
...