有人知道如何在Python中从多维数组中提取列吗?
当前回答
您是否使用了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]
其他回答
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_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]
如果你有一个数组
a = [[1, 2], [2, 3], [3, 4]]
然后像这样提取第一列:
[row[0] for row in a]
结果是这样的:
[1, 2, 3]
如果你想抓取多个列,可以使用slice:
a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(a[:, [1, 2]])
[[2 3]
[5 6]
[8 9]]
我认为你想从一个数组中提取一个列,比如下面的数组
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中做的一样。