[英]Getting the index of a timestamp element in a pandas data frame
我有一個 pandas 數據框,我創建如下:
dates = pd.date_range('12-01-2020','12-10-2020')
my_df = pd.DataFrame(dates, columns = ['Date'])
所以這給了
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
我的問題非常基本:用於返回給定日期索引的正確 function 是什么? 我試過my_df['Date'].index('2020-12-05')
,期望得到 4,但我得到了以下錯誤:'RangeIndex' object is not callable。 我也試過
d = pd.TimeStamp('12-05-2020' + '00:00:00')
my_df['Date'].index(d)
但我得到了同樣的錯誤......我很困惑,因為我在類似的情況下成功地使用了 .index,例如在帶有整數的列表上。 任何幫助,將不勝感激。
您也可以使用query
而無需重置索引
my_df.query("Date == '2020-12-05'").index.values[0]
或者如果您想將值分配給搜索:
d = pd.to_datetime('12-05-2020')
my_df.query("Date == @d").index.values[0]
或沒有loc
或query
my_df[my_df.Date == '12-05-2020'].index.values[0]
而你的回答:
4
您可以重置索引
my_df.reset_index().loc[my_df.Date == '2020-12-05', 'index']
或得到標量
my_df.reset_index().loc[my_df.Date == '2020-12-05', 'index'].values[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.