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

其他回答

尽管使用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], [2, 3], [3, 4]]

然后像这样提取第一列:

[row[0] for row in a]

结果是这样的:

[1, 2, 3]

所有列从一个矩阵到一个新的列表:

N = len(matrix) 
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]
>>> 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])

你也可以用这个:

values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]

注意:这对于内置数组和未对齐的数组无效(例如np.array([[1,2,3],[4,5,6,7]]))