How to sum columns of an array in Python

前端 未结 12 1057
抹茶落季
抹茶落季 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:50

    You may also use sum with zip within the map function:

    # In Python 3.x 
    >>> list(map(sum, zip(*input_val)))
    [3, 6, 9, 12, 15]
    # explicitly type-cast it to list as map returns generator expression
    
    # In Python 2.x, explicit type-casting to list is not needed as `map` returns list
    >>> map(sum, zip(*input_val))
    [3, 6, 9, 12, 15]
    
    0 讨论(0)
  • 2021-01-04 10:52

    I guess you can use:

    import numpy as np
    new_list = sum(map(np.array, input_val))
    
    0 讨论(0)
  • 2021-01-04 10:56
    output_val=input_val.sum(axis=0)
    

    this would make the code even simpler I guess

    0 讨论(0)
  • 2021-01-04 11:00

    In case you decide to use any library, numpy easily does this:

    np.sum(input_val,axis=0)

    0 讨论(0)
  • 2021-01-04 11:03

    Try this code. This will make output_val end up as [3, 6, 9, 12, 15] given your input_val:

    input_val = [[1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5]]
    
    vals_length = len(input_val[0])
    output_val = [0] * vals_length # init empty output array with 0's
    for i in range(vals_length): # iterate for each index in the inputs
        for vals in input_val:
            output_val[i] += vals[i] # add to the same index
    
    print(output_val) # [3, 6, 9, 12, 15]
    
    0 讨论(0)
  • 2021-01-04 11:04

    I think this is the most pythonic way of doing this

    map(sum, [x for x in zip(*input_val)])
    
    0 讨论(0)
提交回复
热议问题