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


当前回答

您是否使用了NumPy数组?Python有array模块,但不支持多维数组。普通的Python列表也是一维的。

然而,如果你有一个简单的二维列表,像这样:

A = [[1,2,3,4],
     [5,6,7,8]]

然后你可以像这样提取一个列:

def column(matrix, i):
    return [row[i] for row in matrix]

提取第二列(索引1):

>>> column(A, 1)
[2, 6]

或者简单地说:

>>> [row[1] for row in A]
[2, 6]

其他回答

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]

如果你有一个数组

a = [[1, 2], [2, 3], [3, 4]]

然后像这样提取第一列:

[row[0] for row in a]

结果是这样的:

[1, 2, 3]

假设我们有nxm矩阵(n行m列)5行4列

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]]

要在python中提取列,我们可以像这样使用列表推导式

[ [row[i] for row in matrix] for in range(4) ]

你可以用矩阵的列数来替换4。 结果是

,10,14,18,5,9,13,17 [[1], [2], [3,7,11,15,19], [4,8,12,16,20]]

如果你喜欢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)

我更喜欢下一个提示: 将矩阵命名为matrix_a并使用column_number,例如:

import numpy as np
matrix_a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
column_number=2

# you can get the row from transposed matrix - it will be a column:
col=matrix_a.transpose()[column_number]