首页 > 解决方案 > 重新索引 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)

标签: python-3.xpandasfinancepandas-datareader

解决方案


您需要将两个索引都转换为 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]

推荐阅读