gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:46:46 24 4
gpt4 key购买 nike

这是我的代码,

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 作为索引,而不是原始数据框中的日期。那么如何纠正这个问题呢?

最佳答案

如果你想让索引过来,你就得给它赋值。这里有两种似乎有效的方法:

>>> 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

关于pandas - 如何创建以日期为索引的 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com