2015-07-20 97 views
1

我使用Python的Pandas从Yahoo Finance获得一些财务数据,这是pandas_datareader的内置功能。我想访问它打印出的日期,但它似乎并没有在列,也不在我需要,但JSON是那里当我打印出来的对象:如何访问Pandas的DataReader中的日期行?

from pandas_datareader.data import DataReader 
import datetime 

start = datetime.datetime(2015, 6, 1) 
goog = DataReader('GOOGL', 'yahoo', start) 
goog.to_json(None, orient="records") # this doesn't include dates! 
print(goog) # this prints out the dates along with the other data! 
print(goog.columns) # prints every column except the date column 

我怎么能包括沿日期与JSON字符串中的其他数据?

回答

1

熊猫数据框有一个用于分组和快速查找的索引。该索引不被视为其中一列。要将索引中的日期从索引移动到列,可以使用reset_index(),这将使Date成为一列,并使索引只是从0开始计数的一系列数字。

因此,要导出为包含日期的JSON:

goog.reset_index().to_json(None, orient='records', date_format='iso') 
2

list(goog.index)为您提供日期列表的时间戳。

为了在json中获取日期,我快速浏览了docs。试试这个:

print goog.to_json(orient="index", date_format='iso') 
+0

有没有一种优雅的方式来合并列表与数据的重置,所以我可以更容易地导出到JSON? – nico

+0

@ Guy3000更好? – bananafish

+0

reset_index()完全解决了我的问题,但这肯定是朝着正确方向迈出的第一步,谢谢! – nico