[英]Getting the index of a timestamp element in a pandas data frame
I have a pandas data frame that I created as follows:我有一个 pandas 数据框,我创建如下:
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?我的问题非常基本:用于返回给定日期索引的正确 function 是什么? 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.我试过my_df['Date'].index('2020-12-05')
,期望得到 4,但我得到了以下错误:'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.但我得到了同样的错误......我很困惑,因为我在类似的情况下成功地使用了 .index,例如在带有整数的列表上。 Any help would be appreciated.任何帮助,将不胜感激。
You can also use query
without having to reset the index您也可以使用query
而无需重置索引
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
或没有loc
或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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.