A vector of size n . How to sum every m values ​​from a given vector? That is, the first three, the second three, and so on. At the output, get the vector of sums of size n / m . Thank you in advance.

  • Can you add a sample data and expected result to the question? Sample data would be good for the code :) - gil9red

4 answers 4

 items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] n = len(items) m = 3 new_items = [] for i in range(n // m): new_items.append(sum(items[i * m: i * m + m])) print(new_items) # [3, 12, 21, 30] 
     result = [sum(a[i:i+m]) for i in range(0, n, m)] 

      Common decision.

       def sum_norm(x, y): d = [] n = len(y) m = len(x) rng = round(n/m) for i in range(rng): d.append(np.sum(y[i*m:i*m+m])) return d 
      • one
        It’s good that you did it yourself :) A couple of notes on formatting: 4 spaces are indented, do not use uppercase variables - they are considered constants (although no one bothers to change them), you have a lot of extra parentheses, as if I look at a list: ) rng = (round(n/m)) -> rng = round(n/m) , D.append(np.sum(d[i*m : i*m+m)]) , in the names of functions / methods in lower case, and in upper case in camel notation, classes are usually called: SumNorm -> sum_norm - gil9red
      • one
        @gil9red corrected, thanks for the comments. - iamfina

      An example of a vectorized solution using the Pandas module:

       In [235]: import pandas as pd In [236]: v = np.random.randint(100, size=(20)) In [237]: v Out[237]: array([84, 58, 86, 81, 36, 3, 15, 30, 82, 90, 69, 63, 80, 92, 60, 8, 8, 5, 86, 33]) In [238]: s = pd.Series(v) In [239]: s Out[239]: 0 84 1 58 2 86 3 81 4 36 5 3 6 15 .. 13 92 14 60 15 8 16 8 17 5 18 86 19 33 Length: 20, dtype: int32 In [240]: m = 3 In [241]: s.groupby(np.arange(len(s)) // m).sum() Out[241]: 0 228 1 120 2 127 3 222 4 232 5 21 6 119 dtype: int32 In [242]: s.groupby(np.arange(len(s)) // m).sum().values Out[242]: array([228, 120, 127, 222, 232, 21, 119]) In [243]: s.groupby(np.arange(len(s)) // m).sum().values.tolist() Out[243]: [228, 120, 127, 222, 232, 21, 119]