首页 > 解决方案 > 如何从 Pandas 数据框中提取与日期对应的值?

问题描述

我有这个股票市场市盈率数据框,我想从中获取与单个日期对应的数据。但是,以下代码会引发错误。

from nsepy import get_index_pe_history
from datetime import date

nifty_pe = get_index_pe_history(symbol="NIFTY",                             
start=date(2011,1,1), end=date(2015,1,10))
print(type(nifty_pe))
print(nifty_pe.loc[nifty_pe["Date"] == "2014-12-12","P/E"].to_numpy())

数据 nifty_pe 如下所示:

              P/E   P/B  Div Yield
  Date                              
 2011-01-03  24.57  3.88       1.01
 2011-01-04  24.53  3.87       1.01
 2011-01-05  24.26  3.83       1.03

我得到的错误是:

Traceback (most recent call last):
  File "/Users/shyam/venv/DrFinance/lib/python3.7/site-    packages/pandas/core/indexes/base.py", line 2657, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in     pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Date'

标签: pythonpandas

解决方案


Date不是列,而是索引,因此需要按日期使用 date in 进行比较string,但在DatetimeIndexto_datetimefrom python datesto创建之前pandas timestamps

nifty_pe.index = pd.to_datetime(nifty_pe.index)

print(nifty_pe.loc["2011-01-03","P/E"])
24.57

推荐阅读