如何从多维数组中提取列?
有没有人知道怎么从一个多维数组中提取一列数据,在Python里怎么做呢?
20 个回答
110
如果你有一个数组,比如说:
a = [[1, 2], [2, 3], [3, 4]]
那么你可以这样提取第一列:
[row[0] for row in a]
这样得到的结果看起来是这样的:
[1, 2, 3]
289
>>> 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])
nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
另请参见:“numpy.arange”和“reshape”来分配内存
示例:(分配一个形状为矩阵(3x4)的数组)