pandas  FutureWarning 警告⚠️

本文深入探讨了在使用Pandas库进行数据操作时遇到的FutureWarning警告,详细解析了警告出现的原因,即在DataFrame中尝试访问不存在的列名。文章通过具体代码示例展示了如何定位问题,并提供了解决方案,包括使用if条件判断来避免访问不存在的列,以及使用.reindex()作为替代方法,以确保代码在未来版本的Pandas中仍能正常工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pandas  FutureWarning 警告⚠️

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

/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py:1494: 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
  return self._getitem_tuple(key)

pandas文档中提到这个警告:

警告:从0.21.0开始,pandas将显示FutureWarning带有缺少标签的列表的if索引。将来这会提高一个KeyError。请参阅list-like使用列表中缺少键的loc是不推荐使用 

报出警告代码:

    data = data.loc[:, ['title', 'issuer', 'ctime', 'gtime', 'url']]

解释代码警告原因:

这不是错误,这是一个警告。但它告诉你的是,你的一个标签,可能是你的列标签,没有包含在DataFrame中。当前行为将以静默方式失败并返回带有NaNs 的列。将来,它会引发错误。 

 经过自己Debug,发现了DataFrame数据中确实没有'ctime' 'gitme' 'url' 

修改代码: 此时代码运行不会再抛出警告信息

    # 加个if判断
    if sort == 'SY304000':
        data = data.loc[:, ['title', 'issuer', 'ctime']]
    else:
        data = data.loc[:, ['title', 'issuer', 'ctime', 'gtime', 'url']]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ch3nnn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值