【问题标题】:FutureWarning: .loc or [] with missing label, suggests to use .reindex() [duplicate]FutureWarning:.loc 或 [] 缺少标签,建议使用 .reindex() [重复]
【发布时间】:2019-02-25 20:25:55
【问题描述】:

我的输入数据框有四分之一格式的DateRateDate 中缺少四分之一。现在我正在尝试根据逻辑计算Update,如果最后一个季度的第三行可用,则选择此速率,否则选择最后一行的速率。我当前的代码如下所示:

# Create dataframe
df1 = pd.DataFrame([[1, '2015Q3'], [2, '2015Q4'], 
                    [6, '2017Q1'], [7, '2017Q4'], 
                    [9, '2018Q1'], [3, '2018Q2'],
                    [5, '2018Q3'], [4, '2018Q4']],
                  columns=['Rate', 'Date'])
df1.index = pd.PeriodIndex(df1.Date, freq='Q')
df1.drop(columns='Date', inplace=True)

# This Code produces 'FutureWarning' message
df1['Update'] = np.where(np.in1d(df1.index - 3, df1.index.values),
                         df1.loc[df1.index - 3].Rate, df1.Rate.shift(1))

完整的警告信息如下:

FutureWarning: 
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

See the documentation here:
https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike

警告中的链接:deprecate-loc-reindex-listlike

我了解,由于我的 index 进行了算术计算,并且计算中的某些 index 值不存在,这导致了此警告消息并建议使用 pandas.DataFrame.reindex。虽然我的意图是仅在 index 可用时才能访问 Rate p>

我尝试扩展Date 范围,但在边界附近也会出现同样的问题。所以,现在我的问题是如何解决这个警告信息。任何见解/想法/信息/链接都会有所帮助。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    问题在于,在准备 np.where 可能需要或不需要的内容时,df.loc[df.index - 3] 会针对 df.index - 3 的所有值进行评估。警告信息很好,建议您改用df.reindex(df.index - 3)

    df1['Update'] = np.where(np.in1d(df1.index - 3, df1.index.values),
                             df1.reindex(df1.index - 3).Rate, df1.Rate.shift(1))
    

    【讨论】:

    • 非常感谢@piRSquared,警告已删除。从链接中显示的示例来看,并不清楚必须以这种方式使用它。
    猜你喜欢
    • 2018-10-18
    • 2020-01-09
    • 2021-10-23
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多