所以我发誓我遇到了一个bug,但我希望有人能证明我错了。
我可以用两种不同的格式制作Pandas DataFrame,第二种是我无法使用的格式。第一种格式如下:
1. open ... 8. split coefficient
date ...
1998-01-02 129.63 ... 1.0
1998-01-05 131.25 ... 1.0
1998-01-06 129.75 ... 1.0
1998-01-07 129.88 ... 1.0
1998-01-08 128.63 ... 1.0
1998-01-09 130.06 ... 1.0
1998-01-12 124.62 ... 1.0
1998-01-13 129.50 ... 1.0
1998-01-14 132.13 ... 1.0
[5292 rows x 8 columns]
我正在尝试选择一个日期最接近指定日期的行/条目。我这样做的功能如下:
def nearest(items, pivot):
nearest_date = min(items, key=lambda x: abs(dt.strptime(x, '%Y-%m-%d') - dt.strptime(pivot, '%Y-%m-%d')))
return nearest_date
然后正确地从对应于该条目的第四列中获得一个值:
market = (data.loc[nearest(data.index.get_values(), date)]['4. close'])
然而,在第二种格式中,我的DataFrame看起来像这样(使用基于整数的索引):
date ... 8. split coefficient
0 1998-01-02 ... 1.0
1 1998-01-05 ... 1.0
2 1998-01-06 ... 1.0
3 1998-01-07 ... 1.0
4 1998-01-08 ... 1.0
5 1998-01-09 ... 1.0
6 1998-01-12 ... 1.0
7 1998-01-13 ... 1.0
8 1998-01-14 ... 1.0
[5292 rows x 9 columns]
因此,我相应地调整了我的"市场"等式:
market = (data.loc[nearest(data['date'].values, date)]['4. close'])
得到这个错误:
KeyError: 'the label [2019-01-14] is not in the [index]'
我尝试过各种疯狂的东西,包括将日期列转换为pd.datetime,但从未出现错误。你所看到的对我来说是有意义的,这就是为什么这是本文尝试的解决方案。有什么问题吗?
然后仅reset_index
返回
data.reset_index(inplace=True)
做
market = (data.loc[nearest(data['date'].values, date)]['4. close'])