有人知道如何在Python中从多维数组中提取列吗?
当前回答
所有列从一个矩阵到一个新的列表:
N = len(matrix)
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]
其他回答
>>> 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], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
它和上面的是一样的,只是它更整洁一些 zip可以完成这项工作,但需要单个数组作为参数,*a语法将多维数组解压缩为单个数组参数
所有列从一个矩阵到一个新的列表:
N = len(matrix)
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]
如果你在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)