Scott
Scott

Reputation: 438

Iterate through defined Datetime index range in Pandas Dataframe

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?

Upvotes: 3

Views: 2073

Answers (1)

jezrael
jezrael

Reputation: 862581

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]

Upvotes: 4

Related Questions