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

Python滑动窗口代码报TypeError:'int' object is not subscriptable求助

问题原因与解决方案

报错触发原因

  • 核心报错点来自代码中的j[0]写法:j是遍历滑动窗口元素得到的单个整数类型值,整数不支持下标索引操作,因此直接抛出TypeError: 'int' object is not subscriptable。
  • 逻辑与需求不符:你需要判断的是每个滑动窗口的第一个元素是否为1,不需要嵌套遍历窗口内部的所有元素,冗余的嵌套循环导致逻辑完全偏离需求。
  • 赋值索引错误:df1['Improved'][j]中的j是窗口内的数值,不是DataFrame的行索引,会导致赋值位置错误,同时触发Pandas链式赋值风险。
  • 变量命名不规范:使用Python内置关键字list作为变量名,会覆盖内置方法,容易引发其他隐性问题。

修正后代码

import pandas as pd
import numpy as np

def GetShiftingWindows(data, size):
    return [data[x:x+size] for x in range(len(data) - size + 1)]

df = [0, 0, 1, 0, 0, 1, 1]
df1 = pd.DataFrame(df, columns=['Labels'])
# 初始值直接设为0,仅符合条件的行修改为1即可
df1['Improved'] = 0

windows = GetShiftingWindows(df1['Labels'], 3)
# 遍历窗口时同时获取窗口对应的起始行索引
for idx, window in enumerate(windows):
    # 仅判断窗口第一个元素是否为1
    if window.iloc[0] == 1:
        # 用loc安全赋值到对应行
        df1.loc[idx, 'Improved'] = 1

# 打印验证结果
for idx, window in enumerate(windows):
    print(window.tolist())
    print(df1.loc[idx, 'Improved'])

运行输出

[0, 0, 1]
0
[0, 1, 0]
0
[1, 0, 0]
1
[0, 0, 1]
0

完全匹配预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:15:02