有人知道如何在Python中从多维数组中提取列吗?


当前回答

[matrix[i][column] for i in range(len(matrix))]

其他回答

你也可以用这个:

values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]

注意:这对于内置数组和未对齐的数组无效(例如np.array([[1,2,3],[4,5,6,7]]))

如果你喜欢map-reduce风格的python, itemgetter操作符也会有帮助,而不是列表推导式,为了一点变化!

# tested in 2.4
from operator import itemgetter
def column(matrix,i):
    f = itemgetter(i)
    return map(f,matrix)

M = [range(x,x+5) for x in range(10)]
assert column(M,1) == range(1,11)

另一种使用矩阵的方法

>>> from numpy import matrix
>>> a = [ [1,2,3],[4,5,6],[7,8,9] ]
>>> matrix(a).transpose()[1].getA()[0]
array([2, 5, 8])
>>> matrix(a).transpose()[0].getA()[0]
array([1, 4, 7])
array = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

col1 = [val[1] for val in array]
col2 = [val[2] for val in array]
col3 = [val[3] for val in array]
col4 = [val[4] for val in array]
print(col1)
print(col2)
print(col3)
print(col4)

Output:
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]

所有列从一个矩阵到一个新的列表:

N = len(matrix) 
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]