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.
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
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.