在 pandas 中包含日期列表的 .loc() 行时出错

Error when .loc() rows with a list of dates in pandas

我有以下代码:

import pandas as pd
from pandas_datareader import data as web

df = web.DataReader('^GSPC', 'yahoo')
df['pct'] = df['Close'].pct_change()

dates_list = df.index[df['pct'].gt(0.002)]

df2 = web.DataReader('^GDAXI', 'yahoo')
df2['pct2'] = df2['Close'].pct_change()

我正在尝试 运行 这个:

df2.loc[dates_list, 'pct2']

但是我一直收到这个错误:

KeyError: 'Passing list-likes to .loc or [] with any missing labels is no longer supported,

我猜这是因为 dates_list 中的日期缺少数据。要解决此问题:

    idx1 = df.index
    idx2 = df2.index
    missing = idx2.difference(idx1)
    df.drop(missing, inplace = True)
    df2.drop(missing, inplace = True)

但是我仍然遇到同样的错误。我不明白这是为什么。

请注意,dates_list 是从 df 创建的,因此它包括 索引 there 中存在一些日期(在 df 中)。

然后您读取 df2 并尝试从以下行检索 pct2 只有这些日期。

但是df2中的索引有可能包含 dates_list 中给出的所有日期。 这就是您出现异常的原因。

为避免这种情况,请仅检索索引中 存在 日期的行。 只寻找这样的“允许”(缩小行规范), 你应该通过:

dates_list[dates_list.isin(df2.index)]

运行 仅此一项,您就会看到“允许”的日期(有些日期会 被淘汰)。

因此将违规指令更改为:

df2.loc[dates_list[dates_list.isin(df2.index)], 'pct']