重新索引Pandas数据框仅提供Nans

问题描述 投票:1回答:1

我想做教程Python for Finance, Part I: Yahoo & Google Finance API, pandas, and matplotlib。由于Google API无法正常运行,我使用了IEX数据。当我尝试重新索引pandas数据Frame时,为了有连续的日期,之前可用的所有值都被NaN替换。我认为新索引与两种不同类型的索引有关。我对编程很新,并且在阅读pandas文档后不知道如何解决这个问题。

代码看起来像这样。

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.x pandas finance pandas-datareader
1个回答
0
投票

您需要将索引转换为日期时间dtype

使用pd.to_datetimeDocs

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]
© www.soinside.com 2019 - 2024. All rights reserved.