Python:读取熊猫数据框的日期索引

时间:2020-03-27 04:09:29

标签: python pandas

我有一个熊猫数据框:

df2.index[0:10]
Out[35]: 
Index([2000-01-03 00:00:00, 2000-01-04 00:00:00, 2000-01-05 00:00:00,
       2000-01-06 00:00:00, 2000-01-07 00:00:00, 2000-01-10 00:00:00,
       2000-01-11 00:00:00, 2000-01-12 00:00:00, 2000-01-13 00:00:00,
       2000-01-14 00:00:00],
      dtype='object')

如何转换原始索引以使以下命令起作用?

M = df2.index.get_loc('2000-01-03')   # Not work now

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用pandas.to_datetime函数将给定的索引转换为datetime。您可以在pandas docs

中找到有关pandas.to_datetime的更多信息

尝试一下:

df2.index = pd.to_datetime(df2.index)
print(df2.index.get_loc("2000-01-03"))

输出:

0