简体   繁体   中英

Add elements of a list to all elements in certain columns

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, eg 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?

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM