Skip to main content
 首页 » 编程设计

python : "TypeError: list indices must be integers, not tuple"

2025年05月04日10think

我从 .csv 文件中读取了一个数据集,它是一个二维数组。
现在我想对数据集进行切片并获取其中每个列表的第一个元素。

import numpy as np 
 
rawData = [] 
with open(path) as file: 
    lines = csv.reader(file) 
    for line in lines: 
        rawData.append(line) 
 
dataSet = rawData[0:10] # as the whole dataset is too large, I get the first ten rows to test 
np.array(dataSet) 
labels = dataSet[:,0] 

如果我运行:

print np.shape(dataSet) 
>>>(10, 785) 

我提到了 How to slice a 2D Python Array .但是我仍然遇到这个错误。

请您参考如下方法:

感谢@jonrsharpe。 np.array(dataSet) 只是创建一个新的 numpy 数组,但我没有将它分配给 dataSet。 应该是

result = np.array(dataSet)