如何创建以日期为索引的pandas数据框

3
这是我的代码,
import plotly.plotly as py
import datetime
import pandas
import matplotlib.pyplot as plt
import pandas.io.data as pd


start = datetime.datetime(2016, 2, 1)
end   = datetime.datetime(2016, 2, 11)
#raw = pd.DataReader("tjx", "yahoo", start, end)
rawy = pd.DataReader("tjx", "yahoo", start, end)['Low']

print rawy
print "========================"

columns = ['Low']
newDf = pd.DataFrame(columns=columns)
newDf = newDf.fillna(0)

#newDf[0] = rawy[0]
#newDf[0:1] = rawy[0:1]
#newDf.loc[0] = rawy.loc[0]
newDf.loc[0] = rawy[0]
print newDf

结果如下所示:
Date
2016-02-01    70.470001
2016-02-02    72.309998
2016-02-03    71.000000
2016-02-04    69.720001
2016-02-05    67.900002
2016-02-08    66.820000
2016-02-09    67.519997
2016-02-10    69.279999
2016-02-11    67.410004
Name: Low, dtype: float64
========================
         Low
0  70.470001

如果您查看结果的最后一行,它使用0作为索引,而不是来自原始数据帧的日期。那么请问如何纠正这个问题?
2个回答

2

如果您想要索引出现,就必须进行分配。以下是两种似乎有效的方法:

>>> newDf = pd.DataFrame(data=[rawy[0]], index=[rawy.index[0]], columns=columns)
>>> newDf
                  Low
2016-02-01  70.470001

或者

>>> newDf = pd.DataFrame(rawy.head(1))
>>> newDf
                   Low
 Date
 2016-02-01  70.470001

这将创建新的数据框。现在如何为新值扩展它? - Alexander

1
它使用零作为索引,因为这是您分配给它的值。请尝试使用以下方式。
newDf = pd.DataFrame(columns=columns)
>>> newDf
Empty DataFrame
Columns: [Low]
Index: []

newDf.ix[rawy.index[0]] = rawy[0]  # Or newDf.loc[rawy.index[0]] = rawy[0]
newDf.ix[rawy.index[1]] = rawy[1]

>>> newDf
                  Low
2016-02-01  70.470001
2016-02-02  72.309998

非常感谢您的快速回答! - user3552178
哎呀,如果我把这个代码放在问题的底部,实际上会得到一个“*** KeyError: Timestamp('2016-02-01 00:00:00', tz=None)”错误。我没想到如果你还没有为newDf分配索引,就不能使用.ix方法? - Robert Rodkey
公平地说,我使用了import pandas.io.data as webrawy = web.DataReader("tjx", "yahoo", start, end)['Low']。日期索引是自动分配的。我不确定这个功能与pd.DataReader是否有所不同。另外,我正在使用Pandas 0.17.1版本。你使用的是哪个版本? - Alexander
我使用的是Pandas 0.12.0版本,所以可能是版本问题。在我的示例中,rawy的索引是自动分配的,但是通过"pd.DataFrame(columns=columns)"创建的newDf明显没有。在你的示例中,你是不是在说"将这个值分配给newDf中索引为rawy.index[0](时间戳)的项?如果没有为newDf显式创建索引,那么它是如何工作的?值得注意的是,我在pandas方面可能是中级水平——主要是想看看我有没有漏掉什么东西。 - Robert Rodkey
我是说将索引值为[timestamp]的newDf赋值为rawy[0]。如果该值在索引中不存在,则会被创建。 - Alexander
明白了,听起来像是版本控制的问题(我需要升级)。感谢您回来澄清。 - Robert Rodkey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接