有人知道如何在Python中从多维数组中提取列吗?
当前回答
如果你在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)
其他回答
您是否使用了NumPy数组?Python有array模块,但不支持多维数组。普通的Python列表也是一维的。
然而,如果你有一个简单的二维列表,像这样:
A = [[1,2,3,4],
[5,6,7,8]]
然后你可以像这样提取一个列:
def column(matrix, i):
return [row[i] for row in matrix]
提取第二列(索引1):
>>> column(A, 1)
[2, 6]
或者简单地说:
>>> [row[1] for row in A]
[2, 6]
如果你在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)
假设我们有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]]
>>> x = arange(20).reshape(4,5)
>>> x array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
如果你想要第二列,你可以用
>>> x[:, 1]
array([ 1, 6, 11, 16])
嗯,有点晚了……
如果性能很重要,你的数据是矩形的,你也可以将它存储在一维中,并通过常规切片访问列,例如. ...
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]