重新索引熊猫数据框只会给Nans

时间:2018-09-09 21:00:36

标签: python-3.x pandas finance pandas-datareader

我想做教程Python for Finance, Part I: Yahoo & Google Finance API, pandas, and matplotlib。由于Google API无法正常运行,因此我使用了IEX数据。当我尝试重新索引熊猫数据框以具有连续的日期时,之前可用的所有值都将替换为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)

1 个答案:

答案 0 :(得分:0)

您需要将两个索引都转换为日期时间class User < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.belongs_to :company, foreign_key: true t.belongs_to :platform, foreign_key: true t.string :token t.timestamps end end end

使用foreign_keyDocs

dtype