簡體   English   中英

在 pandas DataFrame 中找不到對應日期的索引

[英]Cannot find index of corresponding date in pandas DataFrame

我有以下帶有Date列的 DataFrame,

0      2021-12-13
1      2021-12-10
2      2021-12-09
3      2021-12-08
4      2021-12-07
          ...    
7990   1990-01-08
7991   1990-01-05
7992   1990-01-04
7993   1990-01-03
7994   1990-01-02

我正在嘗試使用以下代碼在此 DataFrame 中查找特定日期的索引,

# import raw data into DataFrame
df = pd.DataFrame.from_records(data['dataset']['data'])
df.columns = data['dataset']['column_names']    
df['Date'] = pd.to_datetime(df['Date'])
# sample date to search for
sample_date = dt.date(2021,12,13)
print(sample_date)
# return index of sample date
date_index = df.index[df['Date'] == sample_date].tolist()
print(date_index)

程序的output是,

2021-12-13
[]

我不明白為什么。 我已將 DataFrame 中的Date列轉換為DateTime ,並且我正在進行同類比較。

我已經用最少的樣本復制了您的Dataframe 通過更改比較date的方式,如下所示。

import pandas as pd
import datetime as dt
df = pd.DataFrame({'Date':['2021-12-13','2021-12-10','2021-12-09','2021-12-08']})
df['Date'] = pd.to_datetime(df['Date'].astype(str), format='%Y-%m-%d')
sample_date = dt.datetime.strptime('2021-12-13', '%Y-%m-%d')
date_index = df.index[df['Date'] == sample_date].tolist()
print(date_index)

output:

[0]

搜索數據在DataFrame的索引號0

請讓我知道這個是否有任何問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM