【问题标题】:How do you extract a column from a multi-dimensional array?如何从多维数组中提取一列?
【发布时间】:2010-10-28 13:54:18
【问题描述】:

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

【问题讨论】:

    标签: python arrays multidimensional-array extraction


    【解决方案1】:

    可能是您使用的是NumPy array 吗? Python 有 array 模块,但它不支持多维数组。普通的 Python 列表也是一维的。

    但是,如果你有一个像这样的简单二维列表:

    A = [[1,2,3,4],
         [5,6,7,8]]
    

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

    def column(matrix, i):
        return [row[i] for row in matrix]
    

    提取第二列(索引 1):

    >>> column(A, 1)
    [2, 6]
    

    或者,简单地说:

    >>> [row[1] for row in A]
    [2, 6]
    

    【讨论】:

    • 这应该是最佳答案。它在指出 NumPy 中的替代方案时回答了所提出的问题。
    • [row[1] for row in A] 这很优雅。为此投票。
    【解决方案2】:

    如果你喜欢 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)
    

    【讨论】:

    • 使用 itertools.imap 处理大数据
    • 对于我的用例,itemgetter 方法的运行速度比列表理解方法快约 50 倍。 Python 2.7.2,用例是在具有几百行和几百列的矩阵上进行大量迭代。
    【解决方案3】:
    >>> 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”和“reshape”分配内存

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

    nrows = 3
    ncols = 4
    my_array = numpy.arange(nrows*ncols, dtype='double')
    my_array = my_array.reshape(nrows, ncols)
    

    【讨论】:

    • 花了我 2 个小时才发现 [:,2] 猜猜这个功能不在切片的官方文献中?
    • 逗号是什么意思?
    • @Phil [row, col]。逗号分隔。
    • 这个答案怎么会有这么多赞? OP 从未说过这是一个 numpy 数组
    • 用于提取 2 列:A[:,[1,3]] 例如提取第二和第四列
    【解决方案4】:

    如果你有一个像

    这样的数组
    a = [[1, 2], [2, 3], [3, 4]]
    

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

    [row[0] for row in a]
    

    所以结果是这样的:

    [1, 2, 3]
    

    【讨论】:

      【解决方案5】:

      看看吧!

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

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

      【讨论】:

      • 上面是什么?请记住,答案的排序方式并不总是相同。
      • 这很干净,但如果性能是一个问题,它可能不是最有效的,因为它正在转置整个矩阵。
      • 仅供参考,这在 python 2 中有效,但在 python 3 中你会得到生成器对象,它当然是不可下标的。
      • @RishabhAgrahari 无论如何要在 Py3 中做这个 zip?
      • @WarpDriveEnterprises 是的,您必须将生成器对象转换为列表,然后进行下标。例如:a2 = zip(*a); a2 = list(a2); a2[0]
      【解决方案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)
      

      【讨论】:

        【解决方案7】:

        嗯,有点晚了……

        如果性能很重要并且您的数据是矩形的,您也可以将其存储在一维中并通过常规切片访问列,例如...

        A = [[1,2,3,4],[5,6,7,8]]     #< assume this 4x2-matrix
        B = reduce( operator.add, A ) #< get it one-dimensional
        
        def column1d( matrix, dimX, colIdx ):
          return matrix[colIdx::dimX]
        
        def row1d( matrix, dimX, rowIdx ):
          return matrix[rowIdx:rowIdx+dimX] 
        
        >>> column1d( B, 4, 1 )
        [2, 6]
        >>> row1d( B, 4, 1 )
        [2, 3, 4, 5]
        

        巧妙的是,这真的很快。 但是,负索引在这里不起作用!所以你不能通过索引-1访问最后一列或最后一行。

        如果您需要负索引,您可以稍微调整访问器功能,例如

        def column1d( matrix, dimX, colIdx ):
          return matrix[colIdx % dimX::dimX]
        
        def row1d( matrix, dimX, dimY, rowIdx ):
          rowIdx = (rowIdx % dimY) * dimX
          return matrix[rowIdx:rowIdx+dimX]
        

        【讨论】:

        • 我检查了这个方法,检索列的成本比嵌套 for 循环便宜得多。但是,如果矩阵很大,比如 1000*1000,则将 2d 矩阵减少到 1d 会很昂贵。
        【解决方案8】:

        另一种使用矩阵的方法

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

        【讨论】:

          【解决方案9】:
          [matrix[i][column] for i in range(len(matrix))]
          

          【讨论】:

            【解决方案10】:

            矩阵中的所有列都放入一个新列表中:

            N = len(matrix) 
            column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]
            

            【讨论】:

              【解决方案11】:

              您也可以使用它:

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

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

              【讨论】:

                【解决方案12】:

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

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

                现在如果你想获取格式的第三列

                D=array[[3],
                [7],
                [11]]
                

                那你需要先把数组做成矩阵

                B=np.asmatrix(A)
                C=B[:,2]
                D=asarray(C)
                

                现在您可以像在 excel 中一样进行元素计算。

                【讨论】:

                • 虽然这对我有很大帮助,但我认为答案可以短得多:1. A = np.array([[1,2,3,4],[5,6,7, 8],[9,10,11,12]]) 2. A[:, 1] >> 数组([ 2, 6, 10])
                【解决方案13】:

                假设我们有 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]]
                

                要在 python 中提取列,我们可以像这样使用列表推导

                [ [row[i] for row in matrix] for in range(4) ]
                

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

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

                【讨论】:

                • 这会创建一个全新的列表吗?
                【解决方案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)
                

                Python 中的映射函数是另一种方法。

                【讨论】:

                  【解决方案15】:

                  如果你想抓取的不仅仅是一列,只需使用 slice:

                   a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
                      print(a[:, [1, 2]])
                  [[2 3]
                  [5 6]
                  [8 9]]
                  

                  【讨论】:

                    【解决方案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]
                    

                    【讨论】:

                      【解决方案17】:
                      >>> 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])
                      

                      【讨论】:

                      • 这是使用 numpy 吗?
                      • 我在 numpy 之外的 Python3 中找不到任何有关 arange() 的文档。有人吗?
                      • 我认为是张量流,@KevinWMatthews
                      【解决方案18】:

                      只需使用 transpose(),就可以像获取行一样简单地获取列

                      matrix=np.array(originalMatrix).transpose()
                      print matrix[NumberOfColumns]
                      

                      【讨论】:

                        【解决方案19】:
                        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]
                        

                        【讨论】:

                          【解决方案20】:

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

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

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 2020-12-13
                            • 2020-07-20
                            • 2017-05-15
                            • 2013-04-19
                            • 2018-06-25
                            • 1970-01-01
                            • 2018-01-07
                            • 1970-01-01
                            相关资源
                            最近更新 更多