python - 如何从 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'
解决方案
Date
不是列,而是索引,因此需要按日期使用 date in 进行比较string
,但在DatetimeIndex
由to_datetime
from python dates
to创建之前pandas timestamps
:
nifty_pe.index = pd.to_datetime(nifty_pe.index)
print(nifty_pe.loc["2011-01-03","P/E"])
24.57
推荐阅读
- java - Micronaut jasync 配置所需的 SSL 模式失败
- java - Spring Scheduler 运行的线程比配置的多
- python - SQLite 在无法更新条目时插入新条目
- azure-storage - 使用 REST 将 Blob 上传到 Azure 存储时出错 - 请求 URI 中指定的查询参数之一的值无效
- javascript - DOM 就绪事件之前的 URL 属性
- javascript - Onchange 提交给我错误-javascript
- ruby - 尝试安装 gem 时出现此 LoadError 的原因可能是什么?
- file-upload - 将数据帧作为镶木地板文件直接发送到保管箱
- list - 在 Kotlin 中是否有比“双重平面映射”更简洁/可读的过滤方式?
- python - 从字典的每个数据框中提取具有相同名称的列