检索TypeError:“int”对象不可下标

2024-06-14 11:17:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经应用了窗口大小为3的示例代码,现在我需要GetShiftingWindows提供的窗口的第一个值,该值基于一个条件(如果等于1),并将该值存储在数据帧的第二列中

例如,我正在检索的输出在下面,如果它等于1,我需要列表的第一个值,但在下面的输出中,它没有按预期工作,并且提供错误

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

代码 预期的预期输出

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

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'])
df1['Improved']=np.NaN

list=GetShiftingWindows(df1['Labels'], 3)


for i in list:
  for index, j in enumerate(i,start=1):
    if j==1:
       df1['Improved'][j]=j[0]

检索以下错误:

TypeError Traceback (most recent call last)
<ipython-input-27-bb0991d40acd> in <module>()
      3       for index, j in enumerate(i,start=1):
      4         if j==1:
----> 5            df1['Improved'][j]=j[0]
TypeError: 'int' object is not subscriptable

Tags: 代码indffordatasizeindexlabels
1条回答
网友
1楼 · 发布于 2024-06-14 11:17:13

你在一个数组上循环,你说如果有一个元素是1,你需要列表的第一项

for i in list:
  for index, j in enumerate(i,start=1):
    if j==1:
       # Change here, i[0] is the first element 
       df1['Improved'][j]=i[0]

相关问题 更多 >