2016-03-05 30 views
2

我有一個CSV文件存儲時代的學生人數已經嘗試每個問題,它的格式如下的Python:在列表或陣列存儲CSV數據

UserID Q1 Q2 Q3 Q4 
20  1 2 3 1 
21  0 1 2 1 

我想寫一個python程序將數據存儲到數組attempts_count

attempts_count = numpy.zeros(shape=(2000,200,200)) 
with open('Question_Attempts_Worksheet_1.csv' , 'r') as csvfile: 
     csvfile.readline() # skip the first line(column title) 
     for line in csvfile: 
      csv_row = line.split() 
      user_id = csv_row[0] 
      for question_counter in range(0,4): 
       attempts_count[user_id][1][question_counter] += csv_row[question_counter + 1] 

我希望能獲得attempts_count[20][1][0]=1attempts_count[20][1][2]=3

但是,我得到了一個錯誤信息說

"IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices".

可我知道我應該怎麼解決這個問題?

+1

你有沒有考慮導入' csv'模塊?它會自動分析您的CSV文件,並允許您訪問單獨的行和列,而無需手動分析行並通過分隔符分割。 – Terry

回答

2

解決此問題的最佳方法是使用csv包,因爲該文件格式爲csv。這是怎麼回事可以用csv包來完成:

attempts_count = numpy.zeros(shape=(2000,200,200)) 
with open ('Question_Attempts_Worksheet_1.csv' , 'r') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',') 
    next(reader, None) # skip the headers 
    for row in reader: 
     for question_counter in range(0,4): 
      attempts_count[int(row[0])][1][question_counter] += int(row[question_counter + 1]) 

但是,從你的代碼進行,至少有三個問題可以在代碼來識別。

第一個問題與你的userId,因爲你從CSV文件中得到它,它是一個string而不是整數。嘗試使用它之前將其轉換爲int

user_id = int(csv_row[0]) #here, get this as integer 

第二個問題是,你似乎並不基於,隔板分割您的CSV行(而CSV文件的列值由逗號分隔)。因此,使用分隔符,更新string.split(',')

csv_row = line.split(',') # put , as separator here 

最後,第三個問題與第一個類似。因爲你希望你的csv_row[question_counter + 1]添加到attemps_count,它必須被轉換爲數字還有:

attempts_count[user_id][1][question_counter] += int(csv_row[question_counter + 1]) 

完整的代碼應該是這樣的:

attempts_count = numpy.zeros(shape=(2000,200,200)) 
with open('Question_Attempts_Worksheet_1.csv' , 'r') as csvfile: 
    csvfile.readline() # skip the first line(column title) 
    for line in csvfile: 
     csv_row = line.split(',') # put , as separator here 
     user_id = int(csv_row[0]) #here, get this as integer 
     for question_counter in range(0,4): 
      attempts_count[user_id][1][question_counter] += int(csv_row[question_counter + 1])