有人知道如何在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)
其他回答
>>> 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)
def get_col(arr, col):
return map(lambda x : x[col], arr)
a = [[1,2,3,4], [5,6,7,8], [9,10,11,12],[13,14,15,16]]
print get_col(a, 3)
Python中的map函数是另一种方法。
[matrix[i][column] for i in range(len(matrix))]
如果你喜欢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)
尽管使用zip(*iterable)来转置一个嵌套列表,如果嵌套列表的长度不同,你也可以使用以下方法:
map(None, *[(1,2,3,), (4,5,), (6,)])
结果:
[(1, 4, 6), (2, 5, None), (3, None, None)]
第一列如下:
map(None, *[(1,2,3,), (4,5,), (6,)])[0]
#>(1, 4, 6)