0

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
pythoo
  • 27
  • 7

1 Answers1

0

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]...
...
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
  • i have a table with returns of shares. And i have events, which sometimes happpen at the weekend. I want to look up the return for the event date. So do you know a way to fill up the table with the returns for weekens with the return from next Monday? – pythoo Dec 22 '19 at 12:49
  • So you want to pass date ```d``` (event date), and get back the returns from ```pandas``` for nearest weekday in the future, right? So you will get back same returns for Saturday, Sunday and Monday, for 3 different event dates, right? – Grzegorz Skibinski Dec 22 '19 at 13:02
  • i just want to get the return of the event date 'd'. And if this is not possible because d is sunday or saturday i want the return of the next day (Monday). – pythoo Dec 22 '19 at 13:14
  • Gotcha, then just do the above transformation to ```d```, before passing it to ```pandas.loc[...]```. It will keep ```d``` as it is for weekdays, and for weekends it will move it to the nearest Monday – Grzegorz Skibinski Dec 22 '19 at 13:31
  • thank you. But I have the problem with days like christmas.. So they are not at the weekend but they are no trading days. e.g. one event was on 23.12 so the loop changed the day on 24.12 but this not a trading day. do u see the proble? – pythoo Dec 22 '19 at 13:35
  • Understood! I added piece to return first next existing date after or on ```d``` from the ```df``` dataframe. – Grzegorz Skibinski Dec 22 '19 at 13:54