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

标签 python arrays csv numpy

我有一个 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".

我可以知道如何解决这个问题吗?

最佳答案

解决此问题的最佳方法是使用 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 文件获取的,所以它是一个 字符串 而不是整数。使用前尝试将其转换为 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] 添加到 attempts_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])

关于Python:将 CSV 数据存储在列表或数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812291/

相关文章:

用于运行可执行文件的python多线程进程

python - 如何在mac上将C的 bool 值更改为python的 bool 值

arrays - 将 Firestore 数据加载到 TableView Swift 4

Python Numpy reshape 错误

php - 解析 json 并通过 PHP 为 NULL 行更新 NULL

javascript - JavaScript 是否填充空数组项?

python - 读取 CSV 数据并将其添加到字典中

ruby - CSV 文件中的重复 header

python - 从列表中删除字典

python - 用于从 3-D 数组中选择具有不同起始索引的相同长度子数组的纯 numpy 表达式