【发布时间】:2017-01-01 01:49:19
【问题描述】:
当我使用我之前的一组数据时,这段代码运行良好。但是,现在我向输入数据集添加了更多列,并且出现索引错误。我不确定如何解决这个问题。任何输入? .以下代码给了我错误:
with open("master_aggregated_monthly.csv", 'rb') as csvfile:
data_reader = csv.reader(csvfile, delimiter = ',', quotechar = '"')
rolling_queue = []
for row in data_reader:
if row[0].lower() == "salesforceid":
continue
# most recent rows go in first
rolling_queue.insert(0,row)
if len(rolling_queue) > 12:
rolling_queue.pop()
id = row[0]
date = row[2]
if id in company_dictionary:
account = company_dictionary[id]
#See if we are at the final event
#get the final event from the list
# most recent date for data collection
if date == "6/1/2016":
new_event = event()
new_event.date = "7/1/2016"
new_event.type = "Current Period"
account.events.append(new_event)
my_event = account.events[0]
for entry in rolling_queue:
# don't do anything if the entry in the rolling queue is not from the same account
if entry[0] != id:
continue
nonzero_row = False
# loop through the entries in the rolling queue to find at most the last 12 months of data
for i in range(3, len(entry)):
try:
my_event.attributes[i-3] += float(entry[i])
except:
#handle all of the odd string things
temp = entry[i].split(' ')
if temp[0] == '':
temp = float(temp[1])
else:
temp = float(temp[0])
my_event.attributes[i-3] += temp
# discover if this row is nonzero
if entry[i] != 0 and entry[i] != '0':
nonzero_row = True
# don't include this rown in the average if it's a zero row
if nonzero_row:
#print "Month increment"
my_event.months += 1
这段代码给了我以下错误
<type 'exceptions.IndexError'>
Traceback (most recent call last):
File "P:/Testing/The Scripts, JIC Test/Q4_12month.py", line 116, in main
my_event.attributes[i-3] += temp
IndexError: list index out of range
【问题讨论】:
-
你应该在第 116 行断点并查看 my_event.attributes 实际包含的内容
-
您应该花一些时间并正确格式化这篇文章(尤其是您的代码,因为它是 python)。其次,您需要拉出并突出显示您遇到问题的特定行(我们如何知道第 116 行引用了什么?),最好是一个最小的、可验证的完整示例。请参阅sscce 了解更多信息。
-
增加的数据列的长度可能反映在增加的任何
event变量包含的长度上。并且,因此增加了i的值。随后,i-3。但是,my_event.attributes的长度可能保持不变。因此,IndexError.
标签: python python-2.7 indexing