0

My dataframe looks like this: Dataframe

I am trying to select the values between two months. I have already calculated a while loop which selects the start of the month and the end of the month

start_date = date(2014, 1, 1)
end_date = date(2019, 12, 1)

while start_date <= end_date:
    end_of_month = start_date + relativedelta(months=1, days=-1)

    print (start_date.strftime("%Y-%m-%d"))
    print (end_of_month.strftime("%Y-%m-%d"))    

    start_date = start_date + relativedelta(months=+1)

I always got an error message and so i wanted to try if i can select dates without the loop:

start_date = date(2014, 1, 1)
end_date = date(2019, 12, 1)
Portfolio.loc[start_date:end_date]

I always get the error message KeyError: datetime.date(2014, 1, 1), but i don't know why? Even if i only wanter to filter a single Date: Portfolio.loc[start_date]

fhebe12
  • 69
  • 5
  • Try printing `type(Portfolio.index[0])` and `type(date(2014, 1, 1))`. If they are different, then you need to convert one of them to the other one type. – enzo Sep 06 '20 at 14:27
  • Thanks for your help! Indeed, my index is a different type. I tried to convert it using pd.to_datetime, but i need `datetime.date`. But this turns my index into `pandas._libs.tslibs.timestamps.Timestamp` Do you know how to convert it to a `Datetime.date` object? – fhebe12 Sep 06 '20 at 14:31
  • Try using the method explained in [this question](https://stackoverflow.com/questions/58593741/pandas-to-pydatetime-not-working-inside-a-dataframe) and let me know if it works. – enzo Sep 06 '20 at 14:47
  • I did a little work around: `Portfolio['Datetime'] = pd.to_datetime(Portfolio['Date']) Portfolio = Portfolio.set_index('Datetime')` and this workes fine now – fhebe12 Sep 06 '20 at 14:48

0 Answers0