有人知道如何在Python中从多维数组中提取列吗?
当前回答
>>> import numpy as np
>>> A = np.array([[1,2,3,4],[5,6,7,8]])
>>> A
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> A[:,2] # returns the third columm
array([3, 7])
参见:"numpy。“Arange”和“重塑”来分配内存
示例:(用矩阵(3x4)的形状分配数组)
nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
其他回答
我更喜欢下一个提示: 将矩阵命名为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]
如果你喜欢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)
我认为你想从一个数组中提取一个列,比如下面的数组
import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
现在如果你想要得到格式中的第三列
D=array[[3],
[7],
[11]]
然后你需要首先把数组变成一个矩阵
B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)
现在你可以做基于元素的计算就像你在excel中做的一样。
只要使用转置(),就可以像求行一样简单地求列
matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColumns]
如果你有一个数组
a = [[1, 2], [2, 3], [3, 4]]
然后像这样提取第一列:
[row[0] for row in a]
结果是这样的:
[1, 2, 3]