有人知道如何在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)
其他回答
如果你想抓取多个列,可以使用slice:
a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(a[:, [1, 2]])
[[2 3]
[5 6]
[8 9]]
点击这里查看详情!
a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
它和上面的是一样的,只是它更整洁一些 zip可以完成这项工作,但需要单个数组作为参数,*a语法将多维数组解压缩为单个数组参数
另一种使用矩阵的方法
>>> from numpy import matrix
>>> a = [ [1,2,3],[4,5,6],[7,8,9] ]
>>> matrix(a).transpose()[1].getA()[0]
array([2, 5, 8])
>>> matrix(a).transpose()[0].getA()[0]
array([1, 4, 7])
>>> 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])
如果你喜欢map-reduce风格的python, itemgetter操作符也会有帮助,而不是列表推导式,为了一点变化!
# tested in 2.4
from operator import itemgetter
def column(matrix,i):
f = itemgetter(i)
return map(f,matrix)
M = [range(x,x+5) for x in range(10)]
assert column(M,1) == range(1,11)