0

I have a pandas data frame that I created as follows:

dates = pd.date_range('12-01-2020','12-10-2020')
my_df = pd.DataFrame(dates, columns = ['Date'])

So this gives

        Date
0 2020-12-01
1 2020-12-02
2 2020-12-03
3 2020-12-04
4 2020-12-05
5 2020-12-06
6 2020-12-07
7 2020-12-08
8 2020-12-09
9 2020-12-10

My question is very elementary: What is the correct function to use for returning the index of a given date? I have tried my_df['Date'].index('2020-12-05'), expecting to get 4, but instead I got the following error: 'RangeIndex' object is not callable. I also tried

d = pd.TimeStamp('12-05-2020' + '00:00:00') 
my_df['Date'].index(d)

but I got the same error...I'm confused because I've used .index successfully in similar situations, such as on lists with integers. Any help would be appreciated.

2 Answers 2

1

You can also use query without having to reset the index

my_df.query("Date == '2020-12-05'").index.values[0]

or if you want to assign the value to search:

d = pd.to_datetime('12-05-2020') 
my_df.query("Date == @d").index.values[0]

or without loc or query

my_df[my_df.Date == '12-05-2020'].index.values[0]

And your answer:

4
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this works. But is there an alternate way that uses .index or .loc, but that doesn't involve resetting the index?
My answer doesn't reset the index
Thanks, I like the third option the best :) It seems to me a more natural way of getting the index.
I do not think you need the .values, you can index directly into the index
0

You could reset the index

my_df.reset_index().loc[my_df.Date == '2020-12-05', 'index']

or to get the scalar

my_df.reset_index().loc[my_df.Date == '2020-12-05', 'index'].values[0]

1 Comment

This seems very cumbersome...there must be an easier way that doesn't require reset_index...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.