如何切片二维Python数组?出现错误:“TypeError: list indices must be integers, not tuple”
我在numpy模块中有一个二维数组,长得像这样:
data = array([[1,2,3],
[4,5,6],
[7,8,9]])
我想从这个数组中切出一些特定的列。比如,我可能只想要第0列和第2列:
data = [[1,3],
[4,6],
[7,9]]
用Python最好的方法怎么做呢?(请不要用for循环)
我觉得这样做可以:
newArray = data[:,[0,2]]
但是结果却是:
TypeError: list indices must be integers, not tuple
8 个回答
5
其实,你写的代码应该没问题……你用的是什么版本的numpy呢?
为了确认一下,下面的代码在任何最近版本的numpy中都应该能正常运行:
import numpy as np
x = np.arange(9).reshape((3,3)) + 1
print x[:,[0,2]]
对我来说,运行结果是:
array([[1, 3],
[4, 6],
[7, 9]])
这就是应该得到的结果……
11
如果你想要切割一个二维列表,下面这个函数可能会对你有帮助。
def get_2d_list_slice(self, matrix, start_row, end_row, start_col, end_col):
return [row[start_col:end_col] for row in matrix[start_row:end_row]]
17
这个错误说得很清楚:数据不是一个numpy数组,而是一个列表的列表。
你可以先尝试把它转换成一个numpy数组:
numpy.array(data)[:,[0,2]]