检查 Pandas 数据框中是否存在日期索引

时间:2021-04-28 01:23:20

标签: python pandas

我已经检查过类似的答案,但似乎对字符串索引有效的方法对日期索引无效:

print("Current ending date is "+str(endDate.date()))
if(endDate.date() not in data.index.values):
     print("Last date does not exist for "+ticker)
     print(data.tail(1))

打印输出

Current ending date is 2021-04-27
Last date does not exist for DAX
            DAX_movement  DAX_movement_5days  DAX_movement_21days  DAX_diff_SP500
Date                                                                             
2021-04-27     -0.003087            0.007853             0.041176             NaN

也试过了:

if(endDate not in data.index.values):
if(endDate.date() not in data.index):
if(endDate not in data.index):

该行明确存在但没有找到,如何检查日期索引是否存在?

1 个答案:

答案 0 :(得分:1)

首先确保索引是日期时间格式

df.index = pd.to_datetime(df.index)

那么,

pd.to_datetime(endDate) not in data.index