有人知道如何在Python中从多维数组中提取列吗?
当前回答
只要使用转置(),就可以像求行一样简单地求列
matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColumns]
其他回答
如果你在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)
我更喜欢下一个提示: 将矩阵命名为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]
假设我们有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]]
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]]
a2 = zip(*a)
a2[0]
它和上面的是一样的,只是它更整洁一些 zip可以完成这项工作,但需要单个数组作为参数,*a语法将多维数组解压缩为单个数组参数