Skip to main content
 首页 » 编程设计

Python:将 CSV 数据存储在列表或数组中

2024年10月24日11oomusou

我有一个 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]=1、attempts_count[20][1][2]=3 等

但是,我收到一条错误消息说

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

请问我该如何解决这个问题?

请您参考如下方法:

解决此问题的最佳方法是使用 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])