Add elements of a list to all elements in certain columns

Viewed 56

Here my "problem": Given a numpy array as

array([[4, 3, 5, 1],
       [2, 3, 3, 4],
       [4, 2, 2, 7]])

what I would like to do now is use a list of values

values = [3, 2]

and add them to all elements of certain columns, e.g. columns 2 and 3 leading to

new_array([[4,6,7,1],
           [2,6,5,4],
           [4,5,4,7]])

How can that be done?

1 Answers
a = np.array([[4, 3, 5, 1],
       [2, 3, 3, 4],
       [4, 2, 2, 7]])

values = [3, 2]

a[:,(1,2)] += values

print(a)

Prints:

[[4 6 7 1]
 [2 6 5 4]
 [4 5 4 7]]
Related