想象一下我在python中有这个代码:
import pickle
import numpy as np
import pandas as pd
x_u = []
load_model = open('dt.plk', 'rb')
dt = pickle.load(load_model)
cuantos = int(input('cuantas observaciones: '))
x_u[0] =pd.DataFrame(np.random.randint(341, size = 1))
x_u[1] =pd.DataFrame(np.random.randint(291, size = 1))
x_u[2] =pd.DataFrame(np.random.randint(150, size = 1))
x_u[3] =pd.DataFrame(np.random.randint(301, size = 1))
x_u[4] =pd.DataFrame(np.random.randint(341, size = 1))
x_u[5] =pd.DataFrame(np.random.randint(299, size = 1))
x_u[6] =pd.DataFrame(np.random.randint(150, size = 1))
x_u[7] =pd.DataFrame(np.random.randint(301, size = 1))
ps = dt.predict(x_u)
for d in x_u[0].tolist():
if d == 0:
print('Se queda')
else:
print('Se va')
当我运行它时,我收到此错误。我一直在修改指数范围而没有成功,你能弄清楚它是什么吗?
Traceback (most recent call last):
File "app.py", line 8, in <module>
x_u[0] =pd.DataFrame(np.random.randint(341, size = 1))
IndexError: list assignment index out of range
答案 0 :(得分:1)
您尝试将值分配给不存在的列表索引。
如果您只想按顺序分配这些索引值,则可以使用.append()
:
list.append(x)的 将项添加到列表的末尾。相当于[len(a):] = [x]。
如此修改,您的代码可能如下所示:
import pickle
import numpy as np
import pandas as pd
x_u = []
load_model = open('dt.plk', 'rb')
dt = pickle.load(load_model)
cuantos = int(input('cuantas observaciones: '))
x_u.append(pd.DataFrame(np.random.randint(341, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(291, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(150, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(301, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(341, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(299, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(150, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(301, size = 1)))
ps = dt.predict(x_u)
for d in x_u[0].tolist():
if d == 0:
print('Se queda')
else:
print('Se va')
当然,如果没有您的输入文件和所需的输入/输出,很难判断这是否是您想要的。