python-3.x - 重新索引 Pandas 数据框仅提供 Nans
问题描述
我想做教程Python for Finance,第 I 部分:Yahoo & Google Finance API、pandas 和 matplotlib。由于 Google API 无法正常工作,我使用了 IEX 数据。当我尝试重新索引 pandas 数据帧以具有连续日期时,之前可用的所有值都将替换为NaN
. 我认为新的索引与两种不同类型的索引有关。我对编程很陌生,阅读熊猫文档后不知道如何解决这个问题。
代码看起来像这样。
Modules used
matplotlib==2.2.3
pandas_datareader==0.6.0
googlefinance.client==1.3.0
pandas==0.23.4
googlefinance==0.7
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader as pdr
import matplotlib.pyplot as plt
from datetime import datetime
# Define the instruments to download. We would like to see Apple, Microsoft and the S&P500 index.
#tickers = ["AAPL","MSFT","SPY"]
# We would like all available data from 01/01/2017 until 9/1/2018.
start_date = datetime(2017,1,1)
end_date = datetime(2018,9,1)
# User pandas_reader.data.DataReader to load the desired data.
aapl_data = pdr.DataReader("SPY",'iex',start_date,end_date, pause = 5)
#ms_data = pdr.DataReader('SPY','iex',start_date,end_date,pause = 5)
print(aapl_data.tail(9))
#print(ms_data.tail(9))
print(aapl_data.index.dtype)
close = aapl_data
# Getting all weekdays between start_date and end_date
all_weekdays = pd.date_range(start=start_date, end=end_date, freq='B')
print(all_weekdays.dtype)
# How do we align the existing prices in adj_close with our new set of dates?
# All we need to do is reindex close using all_weekdays as the new index
close = close.reindex(all_weekdays)
# Reindexing will insert missing values (NaN) for the dates that were not present
print(close)
解决方案
您需要将两个索引都转换为 datetime dtype
。
用途pd.to_datetime
:文档
aapl_data = pdr.DataReader("SPY",'iex',start_date,end_date, pause = 5)
aapl_data.index = pd.to_datetime(aapl_data.index) # converts index to datetime dtype
close = aapl_data
all_weekdays = pd.date_range(start=start_date, end=end_date, freq='B')
close = close.reindex(all_weekdays)
print(aapl_data.index.dtype)
# Output:
datetime64[ns]
print(all_weekdays.dtype)
# Output:
datetime64[ns]
推荐阅读
- reactjs - 如果不将 return 放入 redux-thunk 中,这是否运作良好
- android - Android Motion Layout - 观察过渡结束
- scala - 如何在 scala 中的 json 对象中包含多个项目?
- javascript - 如何欺骗已关闭的 Google 表单(“...不再接受回复”)?我想在截止日期后提交表格
- php - 通过 Laravel 关系获取用户拥有的课程
- android - Activity 在使用 alertDialog 时泄漏了窗口 DecorView
- python - python中的继承(Flask)
- r - 使用包含旧行名和新行名的数据框更改行名
- python - GSDMM 聚类收敛(短文本聚类)
- angular - 在 Promise 中打开 NgbModal 不会在新模式中自动对焦