0

I have a time series dataframe "his" with datetime index out of which I want to extract a certain range of timesteps. The starting point "selected_var_start" is in datetime index format (extracted from another dataframe). I want to extract in total 24 h.

I try do it like this: his = his.iloc[selected_var_start:(selected_var_start+pd.DateOffset(hours=24))]

I get the following error TypeError: cannot do positional indexing on DatetimeIndex with these indexers [DatetimeIndex(['2010-11-12 19:00:00'], dtype='datetime64[ns]', name='Datetime', freq=None)] of type DatetimeIndex

What am I doing wrong?

3
  • 1
    iloc is for "purely integer-location based indexing for selection by position" - use loc instead. Jun 1, 2021 at 13:36
  • If I use his = his.loc[selected_var_start:(selected_var_start+pd.DateOffset(hours=24))] I get "pandas.errors.InvalidIndexError: DatetimeIndex(['2010-11-12 19:00:00'], dtype='datetime64[ns]', name='Datetime', freq=None)"
    – PDistl
    Jun 1, 2021 at 13:44
  • 1
    that's just general advice; if you need a detailed answer, please provide a minimal reproducible example. Jun 1, 2021 at 13:48

2 Answers 2

2

You need to access the first element of selected_var_start. Try this selected_var_start[0]. This will transform you element from DatetimeIndex to simply Timestamp, which works with loc.

his.loc[selected_var_start[0]:(selected_var_start[0]+pd.DateOffset(hours=24))]
1

Use loc with strings

pd.DataFrame(index=pd.date_range('11/01/2010', '12/01/2010')).loc['2010-11-12': '2010-11-13']
1
  • Can I include the time somehow? I guess I would have to use selected_var_start.strftime(dateformat) but i looks like I can use only date but not time during the day?
    – PDistl
    Jun 1, 2021 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.