为矩阵提取可变数量的列

时间:2012-03-21 19:47:31

标签: python matplotlib scipy python-2.7

我想从矩阵中提取出一些指定的列。我的矩阵

matrix=[[1,2,3,4,5],
        [6,7,8,9,10],
        [6,4,3,1,2],
        [2,3,4,5,6]]
expected result: [[3,4],[8,9],[3,1],[4,5]] for 2 columns
expected result in case of 3 column:[[1,2,3],[6,7,8],[6,4,3],[2,3,4]]

我正在尝试使用下面给出的方法:

def func(matrix, p):
     return np.vstack([a[i] for a in matrix])

上面的方法只返回一个列,但我想写一个方法,它接受多列作为输入(例如2& 3列的预期结果),我的输入列数每次都有所不同。请建议一个合适的方法在python中提取这些列。

2 个答案:

答案 0 :(得分:3)

使用纯Python,您可以使用以下嵌套列表解析来提取列157

[[a[i] for i in (1, 5, 7)] for a in matrix]

输入的使用示例:

>>> [[a[i] for i in (0, 1, 2)] for a in matrix]
[[1, 2, 3], [6, 7, 8], [6, 4, 3], [2, 3, 4]]

在这种情况下,如果要提取真正的列切片,还可以使用列表切片:

>>> [a[0:3] for a in matrix]
[[1, 2, 3], [6, 7, 8], [6, 4, 3], [2, 3, 4]]

答案 1 :(得分:1)

如果您更喜欢在Numpy中工作,可以使用切片:

def col_slice(arr, col_start=None, total_cols=None):
    """ take a slice of columns from col_start for total_cols """
    return arr[:,col_start:col_start + total_cols]

示例:

In [22]: col_slice(your_matrix, col_start=2, total_cols=2)
Out[22]:
array([[3, 4],
       [8, 9],
       [3, 1],
       [4, 5]])

In [23]: col_slice(your_matrix, col_start=0, total_cols=3)
Out[23]:
array([[1, 2, 3],
       [6, 7, 8],
       [6, 4, 3],
       [2, 3, 4]])