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

如何获取时间戳索引的整数位置?迭代DataFrame时get_loc调用失败

解决DataFrame datetime索引下获取倒数第N行位置并停止迭代的问题

错误原因

你误用了columns.get_loc()方法——这个方法是用来查找列名在列索引中的位置,而非行索引的位置,不管索引类型是什么,用它查行索引都会报错,之前其他类型索引“正常运行”大概率是巧合(比如行索引值恰好和列名重复)。

正确解决方案

方法1:直接通过整数位置切片迭代(最简便)

如果只是要迭代到倒数第N行之前,不需要先找索引再转位置,直接用iloc做整数位置切片就行:

n = -5
# 迭代范围:所有行去掉最后5行(不包含倒数第5行)
for idx, row in data.iloc[:n].iterrows():
    # 你的迭代逻辑
    print(idx, row)

iloc[:n]在n为负数时,会自动截取到倒数第|n|行之前的所有数据。

方法2:获取datetime索引对应的整数行位置

如果确实需要拿到某个datetime索引的整数位置,要用行索引的get_loc()方法:

n = -5
target_index = data.index[n]
# 获取该datetime索引对应的行位置
row_position = data.index.get_loc(target_index)
# 迭代到该位置之前
for idx, row in data.iloc[:row_position].iterrows():
    # 你的迭代逻辑
    print(idx, row)

注意:如果datetime索引存在重复值,get_loc()会返回布尔数组,这时可以用np.where(data.index == target_index)[0][0]获取第一个匹配的位置

方法3:迭代时计数终止

也可以在迭代过程中计数,到达倒数第N行时直接停止:

stop_at = 5  # 倒数第5行停止
total_rows = len(data)
for i, (idx, row) in enumerate(data.iterrows()):
    if i >= total_rows - stop_at:
        break
    # 你的迭代逻辑
    print(idx, row)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:23:03