How do you extract a column from a multi-dimensional array?

前端 未结 20 2834
感情败类
感情败类 2020-12-02 03:56

Does anybody know how to extract a column from a multi-dimensional array in Python?

相关标签:
20条回答
  • 2020-12-02 04:21

    If you want to grab more than just one column just use slice:

     a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
        print(a[:, [1, 2]])
    [[2 3]
    [5 6]
    [8 9]]
    
    0 讨论(0)
  • 2020-12-02 04:23

    If you have a two-dimensional array in Python (not numpy), you can extract all the columns like so,

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

    Executing this code will yield,

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

    Of course, you can extract a single column by index (e.g. columns[0])

    0 讨论(0)
  • 2020-12-02 04:25
    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)
    

    map function in Python is another way to go.

    0 讨论(0)
  • 2020-12-02 04:26

    You can use this as well:

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

    Note: This is not working for built-in array and not aligned (e.g. np.array([[1,2,3],[4,5,6,7]]) )

    0 讨论(0)
  • 2020-12-02 04:26

    Just use transpose(), then you can get the colummns as easy as you get rows

    matrix=np.array(originalMatrix).transpose()
    print matrix[NumberOfColum]
    
    0 讨论(0)
  • 2020-12-02 04:31

    I think you want to extract a column from an array such as an array below

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

    Now if you want to get the third column in the format

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

    Then you need to first make the array a matrix

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

    And now you can do element wise calculations much like you would do in excel.

    0 讨论(0)
提交回复
热议问题