【问题标题】:Pandas Dataframe KeyError: 'the label [2019-01-14] is not in the [index]'Pandas Dataframe KeyError:“标签 [2019-01-14] 不在 [index] 中”
【发布时间】:2019-06-09 00:56:02
【问题描述】:

所以我发誓我遇到了一个错误,但我希望有人能证明我错了。

我可以生成两种不同格式的 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,但从未得到错误。你所看到的对我来说是有意义的,这就是为什么它是这篇文章中尝试的解决方案。关于问题可能是什么的任何想法?

【问题讨论】:

    标签: python pandas datetime indexing keyerror


    【解决方案1】:

    那就reset_index回来

    data.reset_index(inplace=True)
    

    然后做

    market = (data.loc[nearest(data['date'].values, date)]['4. close'])
    

    【讨论】:

    • 谢谢,我想这不是一个糟糕的临时解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多