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


当前回答

如果你在Python中有一个二维数组(不是numpy),你可以像这样提取所有的列,

data = [
['a', 1, 2], 
['b', 3, 4], 
['c', 5, 6]
]

columns = list(zip(*data))

print("column[0] = {}".format(columns[0]))
print("column[1] = {}".format(columns[1]))
print("column[2] = {}".format(columns[2]))

执行这段代码会得到,

>>> print("column[0] = {}".format(columns[0]))
column[0] = ('a', 'b', 'c')

>>> print("column[1] = {}".format(columns[1]))
column[1] = (1, 3, 5)

>>> print("column[2] = {}".format(columns[2]))
column[2] = (2, 4, 6)

其他回答

另一种使用矩阵的方法

>>> 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])

如果你有一个数组

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

然后像这样提取第一列:

[row[0] for row in a]

结果是这样的:

[1, 2, 3]

只要使用转置(),就可以像求行一样简单地求列

matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColumns]
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]
[matrix[i][column] for i in range(len(matrix))]