有人知道如何在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)

尽管使用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)

嗯,有点晚了……

如果性能很重要,你的数据是矩形的,你也可以将它存储在一维中,并通过常规切片访问列,例如. ...

A = [[1,2,3,4],[5,6,7,8]]     #< assume this 4x2-matrix
B = reduce( operator.add, A ) #< get it one-dimensional

def column1d( matrix, dimX, colIdx ):
  return matrix[colIdx::dimX]

def row1d( matrix, dimX, rowIdx ):
  return matrix[rowIdx:rowIdx+dimX] 

>>> column1d( B, 4, 1 )
[2, 6]
>>> row1d( B, 4, 1 )
[2, 3, 4, 5]

巧妙的是,这真的很快。然而,负索引在这里不起作用!所以你不能通过索引-1访问最后一列或最后一行。

如果您需要负索引,您可以稍微调整访问函数,例如。

def column1d( matrix, dimX, colIdx ):
  return matrix[colIdx % dimX::dimX]

def row1d( matrix, dimX, dimY, rowIdx ):
  rowIdx = (rowIdx % dimY) * dimX
  return matrix[rowIdx:rowIdx+dimX]
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_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]