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

使用df.loc筛选DataFrame指定范围行触发InvalidIndexError求助

解决Pandas筛选区间触发InvalidIndexError的问题

你的错误出在区间筛选的语法上,(df_message['iTOW']==194540000):(df_message['iTOW']==194800000)这种写法不符合Pandas的布尔筛选规则——冒号切片只适用于位置索引(如iloc[1:5])或标签索引(如loc['a':'c']),不能直接用来连接两个布尔条件,所以会触发索引错误。

下面是两种正确的区间筛选写法:

  • 方法一:用逻辑与(&)组合比较条件
    每个条件单独用括号包裹,避免运算符优先级问题:

    selected_rows = df_message.loc[(df_message['iTOW'] >= 194540000) & (df_message['iTOW'] <= 194800000)]
    
  • 方法二:使用between()方法(更简洁)
    Pandas提供了专门的区间判断方法,默认包含两端值:

    selected_rows = df_message.loc[df_message['iTOW'].between(194540000, 194800000)]
    

    如果需要排除两端值,添加inclusive=False参数:

    selected_rows = df_message.loc[df_message['iTOW'].between(194540000, 194800000, inclusive=False)]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 01:52:02