如何切片2D Python数组?失败:"TypeError:列表索引必须是整数,而不是元组"

Jon*_*han 14 python numpy multidimensional-array

我在numpy模块中有一个2d数组,看起来像:

data = array([[1,2,3],
              [4,5,6],
              [7,8,9]])
Run Code Online (Sandbox Code Playgroud)

我想得到一个只包含某些元素列的数组.例如,我可能想要第0列和第2列:

data = [[1,3],
        [4,6],
        [7,9]]
Run Code Online (Sandbox Code Playgroud)

最恐怖的方式是什么?(请不要循环)

我认为这会奏效:

newArray = data[:,[0,2]]
Run Code Online (Sandbox Code Playgroud)

但它导致:

TypeError: list indices must be integers, not tuple
Run Code Online (Sandbox Code Playgroud)

Bat*_*hyX 17

该错误明确表示:数据不是一个numpy数组而是一个列表列表.

首先尝试将其转换为numpy数组:

numpy.array(data)[:,[0,2]]
Run Code Online (Sandbox Code Playgroud)


小智 7

如果您想要切片2D 列表,以下功能可能会有所帮助

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]]
Run Code Online (Sandbox Code Playgroud)


Joe*_*ton 5

实际上,你写的应该工作得很好......你使用的是什么版本的numpy?

只是为了验证,以下内容应该与numpy的任何最新版本完美配合:

import numpy as np
x = np.arange(9).reshape((3,3)) + 1
print x[:,[0,2]]
Run Code Online (Sandbox Code Playgroud)

对我来说,收益率:

array([[1, 3],
       [4, 6],
       [7, 9]])
Run Code Online (Sandbox Code Playgroud)

正如它应该...