3

I can see from here how to iterate through a list of dates from a datetime index. However, I would like to define the range of dates using:

my_df['Some_Column'].first_valid_index()

and

my_df['Some_Column'].last_valid_index()

My attempt looks like this:

for today_index, values  in range(my_df['Some_Column'].first_valid_index() ,my_df['Some_Column'].last_valid_index()):
    print(today_index)

However I get the following error:

TypeError: 'Timestamp' object cannot be interpreted as an integer

How do I inform the loop to restrict to those specific dates?

Scott
  • 446
  • 4
  • 16
  • 1
    Answer was edited, `date_range` return DatetimeIndex, so need `for val in r:`, in your `update` use `today_index` instaed `today_index, values` – jezrael Aug 26 '20 at 08:42

1 Answers1

4

I think you need date_range:

s = my_df['Some_Column'].first_valid_index()
e = my_df['Some_Column'].last_valid_index()

r = pd.date_range(s, e)

And for loop use:

for val in r:
    print (val)

If need selecting rows in DataFrame:

df1 = df.loc[s:e]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252