Search code examples
pythondataframelistmatrixdata-structures

Select column header value for a column with the largest Sum - Matrix


I have a matrix for which I want to pick the value of the column header with the largest sum computed.

matrix= [['a','b','c'],                                                                
          [3, 7, 6],                                                                   
          [1, 3, 5],                                                                   
          [9, 4, 2]]

I compute the sum of this matrix as [13, 14, 13] for which I now want to pick the column header values i.e b with largest column sum.


Solution

  • Transpose, sum and find the maximum column.

    Code:

    matrix = [['a', 'b', 'c'],
          [3, 7, 6],
          [1, 3, 5],
          [9, 4, 2]]
    
    transposed_matrix = list(zip(*matrix[1:]))  
    column_sums = [sum(col) for col in transposed_matrix]  # sum of columns
    max_sum_index = column_sums.index(max(column_sums))
    max_sum_column_header = matrix[0][max_sum_index]
    print("Column header:", max_sum_column_header)
    

    Output:

    Column header: b
    

    Few lines of the same code:

    column_sums = [sum(col) for col in zip(*matrix[1:])]
    max_sum_column_header = matrix[0][column_sums.index(max(column_sums))]
    print("Column header:", max_sum_column_header)