如何从多维数组中提取列?

215 python arrays extraction multidimensional-array

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

小智 202

>>> 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])
Run Code Online (Sandbox Code Playgroud)

另请参阅:"numpy.arange"和"reshape"来分配内存

示例:(分配具有矩阵形状的数组(3x4))

nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
Run Code Online (Sandbox Code Playgroud)

  • 花了我2个小时才发现[:,2]猜测这个特征不是在切片的官方文献中? (8认同)
  • 这个答案怎么会有这么多的赞成?OP从未说过它是一个numpy数组 (8认同)
  • @Phil` [row,col]`.逗号分开. (2认同)
  • 对于提取2列:A [:,[1,3]]例如提取第二和第四列 (2认同)

Mar*_*ler 161

难道你正在使用NumPy阵列吗?Python有阵列模块,但不支持多维数组.普通的Python列表也是单维的.

但是,如果您有一个简单的二维列表,如下所示:

A = [[1,2,3,4],
     [5,6,7,8]]
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样提取一个列:

def column(matrix, i):
    return [row[i] for row in matrix]
Run Code Online (Sandbox Code Playgroud)

提取第二列(索引1):

>>> column(A, 1)
[2, 6]
Run Code Online (Sandbox Code Playgroud)

或者,简单地说:

>>> [row[1] for row in A]
[2, 6]
Run Code Online (Sandbox Code Playgroud)

  • 这应该是最重要的答案。它回答了所提出的问题,同时指出了 NumPy 中的替代方案。 (2认同)
  • `[row[1] for row in A]` 这很优雅。对此投票。 (2认同)

And*_*nin 72

如果你有一个像这样的数组

a = [[1, 2], [2, 3], [3, 4]]
Run Code Online (Sandbox Code Playgroud)

然后你像这样提取第一列:

[row[0] for row in a]
Run Code Online (Sandbox Code Playgroud)

所以结果如下:

[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)


小智 35

看看这个!

a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
Run Code Online (Sandbox Code Playgroud)

它与上面的内容相同,只不过它以拉链完成工作但需要单个数组作为参数,*a语法将多维数组解包为单个数组参数

  • 什么是上面的?请记住,答案并不总是以相同的方式排序. (5认同)
  • 仅供参考,这适用于python 2,但是在python 3中你将获得生成器对象,其中的当前不可订阅. (4认同)
  • @WarpDriveEnterprises 是的,您必须将生成器对象转换为列表,然后进行下标。示例:`a2 = zip(*a); a2 = 列表(a2);a2[0]` (3认同)
  • 这很干净,但如果性能是一个问题,可能不是最有效的,因为它是转置整个矩阵. (2认同)

Pet*_*aul 14

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)
Run Code Online (Sandbox Code Playgroud)

Python中的map函数是另一种方法.


Rus*_*ell 12

如果你在 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]))

Run Code Online (Sandbox Code Playgroud)

执行此代码将产生,

>>> 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)
Run Code Online (Sandbox Code Playgroud)

当然,您可以通过索引提取单个列(例如columns[0]


小智 10

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

如果你想要第二列你可以使用

>>> x[:, 1]
array([ 1,  6, 11, 16])
Run Code Online (Sandbox Code Playgroud)

  • 这是使用numpy? (3认同)
  • 我在 numpy 之外找不到任何关于 Python3 中的 `arange()` 的文档。任何人? (2认同)

ren*_*tov 9

[matrix[i][column] for i in range(len(matrix))]
Run Code Online (Sandbox Code Playgroud)


小智 9

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]
Run Code Online (Sandbox Code Playgroud)


Gre*_*ind 8

如果您喜欢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)
Run Code Online (Sandbox Code Playgroud)


小智 7

你也可以使用它:

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

注意:这不适用于内置数组且未对齐(例如np.array([[1,2,3],[4,5,6,7]]))


小智 6

我想你想从数组中提取一个列,如下面的数组

import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
Run Code Online (Sandbox Code Playgroud)

现在,如果您想获得格式的第三列

D=array[[3],
[7],
[11]]
Run Code Online (Sandbox Code Playgroud)

然后你需要首先使数组成为一个矩阵

B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)
Run Code Online (Sandbox Code Playgroud)

现在你可以像在excel中那样进行元素计算.


小智 6

假设我们有n X m矩阵(n行和m列)说5行和4列

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]]
Run Code Online (Sandbox Code Playgroud)

要提取python中的列,我们可以像这样使用列表理解

[ [row[i] for row in matrix] for in range(4) ]
Run Code Online (Sandbox Code Playgroud)

您可以用矩阵具有的任何列数替换4。结果是

[ [1,5,9,13,17],[2,10,14,18],[3,7,11,15,19],[4,8,12,16,20] ]


Sha*_*wat 5

使用矩阵的另一种方法

>>> 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])
Run Code Online (Sandbox Code Playgroud)


小智 5

只需使用 transpose(),即可像获取行一样轻松获取列

matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColumns]
Run Code Online (Sandbox Code Playgroud)