How to sum columns of an array in Python

前端 未结 12 1056
抹茶落季
抹茶落季 2021-01-04 09:58

How do I add up all of the values of a column in a python array? Ideally I want to do this without importing any additional libraries.

input_val = [[1, 2, 3,         


        
相关标签:
12条回答
  • 2021-01-04 10:38

    Please construct your array using the NumPy library:

    import numpy as np
    

    create the array using the array( ) function and save it in a variable:

     arr = np.array(([1, 2, 3, 4, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5]))
    

    apply sum( ) function to the array specifying it for the columns by setting the axis parameter to zero:

    arr.sum(axis = 0)
    
    0 讨论(0)
  • 2021-01-04 10:40

    Try this:

    input_val = [[1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5]]
    
    output_val = [sum([i[b] for i in input_val]) for b in range(len(input_val[0]))]
    
    print output_val
    
    0 讨论(0)
  • 2021-01-04 10:40

    Using Numpy you can easily solve this issue in one line:

    1: Input

    input_val = [[1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5]]
    

    2: Numpy does the math for you

    np.sum(input_val,axis=0)
    

    3: Then finally the results

    array([ 3,  6,  9, 12, 15])
    
    0 讨论(0)
  • 2021-01-04 10:46

    One-liner using list comprehensions: for each column (length of one row), make a list of all the entries in that column, and sum that list.

    output_val = [sum([input_val[i][j] for i in range(len(input_val))]) \
                     for j in range(len(input_val[0]))]
    
    0 讨论(0)
  • 2021-01-04 10:47

    This should work:

    [sum(i) for i in zip(*input_val)]
    
    0 讨论(0)
  • 2021-01-04 10:48

    zip and sum can get that done:

    Code:

    [sum(x) for x in zip(*input_val)]
    

    zip takes the contents of the input list and transposes them so that each element of the contained lists is produced at the same time. This allows the sum to see the first elements of each contained list, then next iteration will get the second element of each list, etc...

    Test Code:

    input_val = [[1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5]]
    
    print([sum(x) for x in zip(*input_val)])
    

    Results:

    [3, 6, 9, 12, 15]
    
    0 讨论(0)
提交回复
热议问题