有人知道如何在Python中从多维数组中提取列吗?


当前回答

你也可以用这个:

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

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

其他回答

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]
>>> 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)

点击这里查看详情!

a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]

它和上面的是一样的,只是它更整洁一些 zip可以完成这项工作,但需要单个数组作为参数,*a语法将多维数组解压缩为单个数组参数

你也可以用这个:

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

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