newbie1239
newbie1239

Reputation: 35

sum columns of part of 2D array Python

INPUT:

M = [[1,2,3],
    [1,2,3],
    [1,2,3]]

how take the sum of the columns in the two first rows and implement it in the array M

OUTPUT:

M = [[2,4,6],
    [1,2,3]]

Upvotes: 0

Views: 121

Answers (2)

Alex Hall
Alex Hall

Reputation: 36013

M = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

M[:2] = [[a + b for a, b in zip(M[0], M[1])]]

print(M)  # [[5, 7, 9], [7, 8, 9]]

Things to google to understand this:

  • M[:2] =: python slice assignment
  • [... for .. in ...]: python list comprehension
  • for a, b in ...: python tuple unpacking loop

Upvotes: 1

akuiper
akuiper

Reputation: 214927

Use numpy.add.reduceat:

import numpy as np
M = [[1,2,3],
    [1,2,3],
    [1,2,3]]

np.add.reduceat(M, [0, 2])     
# indices [0,2] splits the list into [0,1] and [2] to add them separately, 
# you can see help(np.add.reduceat) for more

# array([[2, 4, 6],
#        [1, 2, 3]])

Upvotes: 1

Related Questions