You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何给Pandas DataFrame添加if语句避免索引错误?

解决方案

当然可行,你可以先把查询结果存到变量里,先判断它是否非空,再执行后续逻辑,就能避免索引错误。

具体代码示例:

# 先获取切片结果
market_state_slice = market_info.loc[before_primary_close, "market_state"]
# 判断结果是否非空
if not market_state_slice.empty:
    has_primary_reopen = market_state_slice.iloc[-1] == 'CTS'
else:
    # 空DataFrame时的自定义处理,比如给变量设默认值
    has_primary_reopen = False  # 也可以根据需求设为None或其他值

这里用到Pandas内置的empty属性来判断DataFrame/Series是否为空,简单直接。空结果时记得给has_primary_reopen设置默认值,避免后续代码里出现未定义变量的问题。

内容的提问来源于stack exchange,提问作者ifrj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:34:57