如何从Pandas数据框中提取与日期相对应的值?

时间:2019-09-03 06:45:52

标签: python pandas

我有这个股市P / E数据框,我想从中获取与单个日期相对应的数据。但是,以下代码将引发错误。

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'

2 个答案:

答案 0 :(得分:1)

Date不是列,而是索引,因此需要在string中按日期比较使用日期,但是要在DatetimeIndex之前由to_datetime创建python datespandas timestamps

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

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

答案 1 :(得分:1)

由于使用get_index_pe_history形成的数据帧已将Date列设置为索引,因此引发了Key错误。在nifty_pe["Date"]中尝试使用索引时,不能将其称为列名。您可以重置索引,然后使用如下编写的代码

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

尽管结果是一个空的数据框。